需求:將中文字串轉換為拼音。本文提供 PinYin 類別,載入 word.data 字典檔 (格式:Unicode碼點 拼音),支援帶/不帶聲調、自訂分隔符輸出。
4E00 yī
4E01 yī
4E02 yǐ
... (每行:十六進位 Unicode 碼點 + 空格 + 拼音)
class PinYin:
def __init__(self, dict_file='word.data'):
self.word_dict = {}
self.dict_file = dict_file
def load_word(self):
if not os.path.exists(self.dict_file):
raise IOError("NotFoundFile")
with open(self.dict_file) as f:
for line in f:
parts = line.split()
if len(parts) >= 2:
self.word_dict[parts[0]] = parts[1]
def hanzi2pinyin(self, string=""):
result = []
if not isinstance(string, unicode): # Py2
string = string.decode("utf-8")
for char in string:
key = '%X' % ord(char)
# 取第一個拼音、去聲調 (最後一字元為數字)、轉小寫
pinyin = self.word_dict.get(key, char).split()[0][:-1].lower()
result.append(pinyin)
return result
def hanzi2pinyin_split(self, string="", split=""):
result = self.hanzi2pinyin(string)
return split.join(result) if split else result
test = PinYin()
test.load_word()
s = "歡迎來到腳本之家"
print("in:", s)
print("out:", test.hanzi2pinyin(s))
print("out:", test.hanzi2pinyin_split(s, "-"))
輸出:
in: 歡迎來到腳本之家
out: ['huan', 'ying', 'lai', 'dao', 'jiao', 'ben', 'zhi', 'jia']
out: huan-ying-lai-dao-jiao-ben-zhi-jia
pypinyin 成熟庫 (支援分詞、多音字、聲調風格)。unicode 判斷,直接處理 str。
from pypinyin import pinyin, Style
print(pinyin("歡迎", style=Style.TONE3)) # [['huan1'], ['ying2']]
自製轉換器適合學習原理,生產環境建議使用 pypinyin。