中文分詞:正向匹配最大算法
正向最大匹配法,對於輸入的一段文本從左至右、以貪心的方式切出當前位置上長度最大的詞。正向最大匹配法是基於詞典的分詞方,其分詞原理是:單詞的顆粒度越大,所能表示的含義越確切。該算法主要分兩個步驟:
- 1、一般從一個字符串的開始位置,選擇一個最大長度的詞長的片段,如果序列不足最大詞長,則選擇全部序列。
- 2、首先看該片段是否在詞典中,如果是,則算為一個分出來的,如果不是,則從右邊開始,減少一個字符,然后看短一點的這個片段是否在詞典中,依次循環,逐到只剩下一個字。
- 3、序列變為第2步驟截取分詞后,剩下的部分序列
代碼實現
#使用正向最大匹配算法實現中文分詞
words_dic = []
def init():
'''
讀取詞典文件
載入詞典
:return:
'''
with open(r"C:\Users\lenovo\PycharmProjects\fenci\venv\dic\dic.txt","r",encoding="utf-8") as dic_input:
for word in dic_input:
words_dic.append(word.strip())#列表
#實現正向匹配算法中的切詞方法
def cut_words(raw_sentence,word_dict):
#統計詞典中最長的詞
max_length = max(len(word) for word in words_dic)
sentence = raw_sentence.strip()
#統計序列長度
word_length = len(sentence)
#存儲切分好的詞語
cut_word_list = []
while word_length > 0:
max_cut_length = min(max_length,word_length)#判斷最長詞語與句子的長度
subsentence = sentence[0:max_cut_length] #子句與就是最大的長度
while max_cut_length > 0:
if subsentence in word_dict:#如果句子是長的,那么從頭便取最大詞的長度,如果在,首詞便框住
cut_word_list.append(subsentence) #如果不在詞典豈不是完蛋了
break
elif max_cut_length == 1:
cut_word_list.append(subsentence)
break
else:
max_cut_length = max_cut_length-1 #大概率是不在的,因此切得長度減1
subsentence = subsentence[0:max_cut_length]
sentence = sentence[max_cut_length:]
words_length = word_length - max_cut_length
if words_length == 0:
break
words = "/".join(cut_word_list)
return words
def main():
'''
與用戶交互接口
:return:
'''
init()
while True:
print("請輸入要分詞序列:")
input_str = input()
if not input_str:
break
result = cut_words(input_str,words_dic)
print("分詞結果")
print(result)
if __name__=="__main__":
main()