python识别一段由字母组成的字符串是拼音还是英文单词

时间:2024-04-30 23:34:26

环境: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”的情况。