OpenCC 是啥?
Python OpenCC 是一個用於中文文本轉換的 Python 庫,它提供了對繁體字和簡體字之間的轉換功能。這個庫建立在 OpenCC 開源專案的基礎上,OpenCC 是一個流行的中文簡繁轉換庫,用於將簡體字轉換為繁體字或反之。
一行安裝
1
pip install opencc-python-reimplemented
例子
我有一段繁體文字,想要轉成簡體文字
林志傑是台灣最棒的籃球員, 姚明是大陸最棒的籃球員。
codes (10 行內搞定一切)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import opencc
file_path = 'basketball_繁.txt'
with open(file_path, 'r') as file:
file_content = file.read()
# 繁轉簡
converter = opencc.OpenCC('t2s')
change_lang = converter.convert(file_content)
with open('basketball_簡.txt', 'w') as file:
file.write(change_lang)
指令解說
- import opencc -> import lib
- with open(file_path, ‘r’) as file … -> 讀取文字檔
- change_lang = converter.convert(file_content) -> 轉換
- with open(‘basketball_簡.txt’, ‘w’) as file: -> 寫回檔案
- converter = opencc.OpenCC(‘t2s’) -> 設定 converter,此步驟最重要,若要其他組合的翻譯,請參考以下設定。
from OpenCC
輸出
林志杰是台湾最棒的篮球员, 姚明是大陆最棒的篮球员。
大量資料實測
實測過資料 11 萬行文字,共 256 萬個字;繁簡互轉,速度及正確性也都十分優秀。 這個特性是最重要的,或許網路上可以找到少量文字的繁簡互翻, 但若文字量過大,恐怕就無法負擔了,所以會寫 python 的人,有此需求的人,趕快把此優秀的 lib 下載來玩玩吧!