python識別一段由字母組成的字符串是拼音還是英文單詞
阿新 • • 發佈:2018-05-01
http ref div txt com out temp max 修復
環境:win10 python3.6
先說一下算法思想:
首先建立本地拼音庫(不帶聲調)。使用貪婪算法將字符串從左向右掃描,將字符串與本地拼音庫(這裏提供給大家一個)進行匹配,當發現匹配成功時繼續掃描,直到不匹配或者結尾為止。重復這個過程
下面是python代碼:
def pinyin_or_word(string):
‘‘‘
judge a string is a pinyin or a english word.
pinyin_Lib comes from a txt file.
‘‘‘
string = string.lower()
stringlen = len(string)
result = []
while True:
i_list = []
for i in range(1,stringlen+1):
if string[0:i] in pinyin_Lib:
i_list.append(i)
if len(i_list) == 0:
print("這是一個英語單詞!")
temp_result = []
break
else:
temp = max(i_list)
result.append(string[0:temp])
string = string.replace(string[0:temp],‘‘)
stringlen = len(string)
if stringlen == 0:
# print("這是一個拼音!")
# print(result)
break
return result
In [1]: pinyin_or_word("woaizhongguo" )
Out[1]: [‘wo‘, ‘ai‘, ‘zhong‘, ‘guo‘]
這裏我封裝成了一個函數:傳參為字符串,輸出“拼音+拼音長度”或者判定英文。
其實這個算法是有缺陷的:
①比如你輸入一個英文單詞‘open‘,將返回拼音‘o‘+‘pen‘
②雖說是判斷拼音或單詞,但是主要應該說是判斷拼音,不能嚴格判斷單詞,想要精確判斷,需添加單詞庫。
關於第二點這個容易修復,第一點暫時想不到解決方法,倘若哪位大俠可以想到,還望指教。
python識別一段由字母組成的字符串是拼音還是英文單詞