PinYin 類完整實現與字典檔說明將漢字轉為拼音是中文 NLP、排序、檢索的基礎需求。本文提供一個零依賴的 PinYin 類,載入 word.data 字典檔(Unicode 碼點 → 拼音映射),支援列表輸出與自定義分隔符。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os.path
class PinYin(object):
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_obj:
for line in f_obj:
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)
# 取第一個拼音、去聲調數字、轉小寫
py = self.word_dict.get(key, char).split()[0][:-1].lower()
result.append(py)
return result
def hanzi2pinyin_split(self, string="", split=""):
result = self.hanzi2pinyin(string)
return split.join(result) if split else result
if __name__ == "__main__":
test = PinYin()
test.load_word()
string = "歡迎來到腳本之家"
print("in: %s" % string)
print("out: %s" % str(test.hanzi2pinyin(string)))
print("out: %s" % test.hanzi2pinyin_split(string, split="-"))
word.data 字典檔格式
# 每行:Unicode碼點(十六進位) 拼音(帶聲調數字)
4E00 yi1
4E8C er4
4E09 san1
... (約 2 萬常用字)
可從開源專案(如 pypinyin、hanzi2pinyin)導出或自行整理。
unicode 判斷,字串預設為 str(Unicode)。open(..., encoding='utf-8') 明確指定編碼。ord(char) 直接可用,'%X' % ord(char) 同。pip install pypinyin,支援多音字、聲調風格、分詞、異體字,業界標準。
from pypinyin import pinyin, Style
print(pinyin("歡迎來到腳本之家", style=Style.TONE3))
# [['huān1'], ['yíng2'], ['lái2'], ['dào4'], ['jiǎo3'], ['běn3'], ['zhī1'], ['jiā1']]
自製 PinYin 適合學習字典查表原理、極簡環境無法 pip install 時使用;正式專案請直接採用 pypinyin,避免維護字典檔與多音字邏輯。