首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 漢字轉拼音庫:PinYin 類別載入字典檔轉換

     編輯:更多程式設計知識

需求:將中文字串轉換為拼音。本文提供 PinYin 類別,載入 word.data 字典檔 (格式:Unicode碼點 拼音),支援帶/不帶聲調、自訂分隔符輸出。

字典檔格式 (word.data)


4E00 yī
4E01 yī
4E02 yǐ
... (每行:十六進位 Unicode 碼點 + 空格 + 拼音)

PinYin 類別


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

改進建議

  1. 支援多音字:回傳列表或上下文消歧。
  2. 使用 pypinyin 成熟庫 (支援分詞、多音字、聲調風格)。
  3. 字典檔改用 JSON/ SQLite 提升載入速度。
  4. Python 3 移除 unicode 判斷,直接處理 str。

pypinyin 範例


from pypinyin import pinyin, Style
print(pinyin("歡迎", style=Style.TONE3))  # [['huan1'], ['ying2']]

自製轉換器適合學習原理,生產環境建議使用 pypinyin。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved