python識別一段由字母組成的字符串是否是拼音


環境:win10 python3.6

先說一下算法思想:
首先建立本地拼音庫(不帶聲調)。使用逆向最大匹配將字符串與本地拼音庫(這里提供給大家一個)進行匹配。話不多說,見code:

def pinyin_or_word(string):
    '''
    judge a string is a pinyin or not.
    pinyinLib comes from a txt file.
    '''
    max_len = 6   # 拼音最長為6
    string = string.lower()
    stringlen = len(string)
    result = []
    while True:
        matched = 0
        matched_word = ''
        if stringlen < max_len:
            max_len = stringlen                
        for i in range(max_len, 0, -1):
            s = string[(stringlen-i):stringlen]
            if s in pinyinLib:
                matched_word = s
                matched = i
                break
        if len(matched_word) == 0:
            break
        else:
            result.append(s)
            string = string[:(stringlen-matched)]
            stringlen = len(string)
            if stringlen == 0:
                break
    return result

In [1]: pinyin_or_word("woaizhongguo")
Out[1]: ['wo', 'ai', 'zhong', 'guo']

其實這個算法是有缺陷的:比如你輸入一個英文單詞'open',將返回拼音'o'+'pen'。
注:正向最大匹配會遇到“xiange”分成“xiang/e”的情況。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM