1. 程式人生 > >Python漢字轉換成拼音

Python漢字轉換成拼音

split() 圖片 git log hub 找到 轉換 res 輸出

轉載自: https://www.cnblogs.com/code123-cc/p/4822886.html

最近在使用Python做項目時,需要將漢字轉化成對應的拼音.在Github上找到了一個現成的程序.

Python漢字轉拼音

使用實例如下:

from pinyin import PinYin

test = PinYin()
test.load_word()
print test.hanzi2pinyin(string=‘釣魚島是中國的‘)
print test.hanzi2pinyin_split(string=‘釣魚島是中國的‘, split="-")

輸出:

[‘diao‘, ‘yu‘, ‘dao‘, ‘shi‘, ‘zhong‘, ‘guo‘, ‘de‘]
‘diao-yu-dao-shi-zhong-guo-de‘

其中hanzi2pinyin函數返回值是一個列表,而hanzi2pinyin_split函數在split參數為空時返回列表,不為空是返回字符串.

但程序存在兩個問題,第一是當中文中夾帶英文時,英文會丟失.第二則是hanzi2pinyin_split的返回值一會是列表,一會是字符串,讓人比較迷糊.

例如:

test.hanzi2pinyin_split(string=‘釣魚島是中國的code123‘, split="")

我們期待的結果是:

u‘diaoyudaoshizhongguodecode123‘

但實際結果為:

u‘diaoyudaoshizhongguode‘

為此,在原來的程序中做了如下改寫.

1.hanzi2pinyin函數修改

原來的hanzi2pinyin函數:

技術分享圖片
def hanzi2pinyin(self, string=""):
    result = []
    if not isinstance(string, unicode):
        string = string.decode("utf-8")
        
    for char in string:
        key = ‘%X‘ % ord(char)
        result.append(self.word_dict.get(key, char).split()[0][:-1].lower())

    return result
技術分享圖片

修改後的hanzi2pinyin函數:

技術分享圖片
def hanzi2pinyin(self, string=""):
    result = []
    if not isinstance(string, unicode):
        string = string.decode("utf-8")

    for char in string:
        key = ‘%X‘ % ord(char)
        if not self.word_dict.get(key):
            result.append(char)
        else:
            result.append(self.word_dict.get(key, char).split()[0][:-1].lower())

    return result
技術分享圖片

修改後的hanzi2pinyin函數可以避免中英文混合的情況下,英文丟失.

2.hanzi2pinyin_split函數修改,將返回值為統一為字符串

原來的hanzi2pinyin_split函數:

def hanzi2pinyin_split(self, string="", split=""):
    result = self.hanzi2pinyin(string=string)
    if split == "":
        return result
    else:
        return split.join(result)

修改後的hanzi2pinyin_split函數(不論split參數是否為空,hanzi2pinyin_split均返回字符串):

def hanzi2pinyin_split(self, string="", split=""):
    result = self.hanzi2pinyin(string=string)
    #if split == "":
    #    return result
    #else:
    return split.join(result)

Python漢字轉換成拼音