完整的代碼和資料見 github:zlhcsm
知識普及:反向最大匹配法的基本原理與正向最大匹配法類似,只是分詞順序變爲從右至左。
步驟
1,一般從一個字符串的結束位置,選擇一個最大長度的詞長的片段,如果序列不足最大詞長,則選擇全部序列。
2,首先看該片段是否在詞典中,如果是,則算爲一個分出來的詞,如果不是,則從左邊開始,減少一個字符,然後看短一點的這個片段是否在詞典中,一次循環,直到只剩下一個字。
3,序列變爲第2步驟截取分詞後,剩下的部分序列
核心代碼
1,讀取文件,由於字典文件格式不一定相同,因此建議採用此文件讀取代碼
def init():
"""
讀取詞典文件
:return:
"""
with open("../dic/dict.txt", "r", encoding="utf8") as dic_input:
for word in dic_input:
words_dic.append(word.split(" ")[0].strip())
2,切詞方法
#實現逆向最大匹配算法中的切詞方法
def cut_words(raw_sentence, words_dic):
# 統計詞典中詞的最長長度
max_length = max(len(word) for word in words_dic)
sentence = raw_sentence.strip()
# 統計序列長度
words_length = len(sentence)
# 存儲切分出來的詞語
cut_word_list = []
# 判斷是否需要繼續訪問
while words_length > 0:
max_cut_length = min(max_length, words_length)
sub_sen = sentence[-max_cut_length:]
while max_cut_length > 0:
if sub_sen in words_dic:
cut_word_list.append(sub_sen)
break
elif max_cut_length == 1:
cut_word_list.append(sub_sen)
break
else:
max_cut_length = max_cut_length - 1
sub_sen = sub_sen[-max_cut_length:]
sentence = sentence[0:-max_cut_length]
words_length = words_length - max_cut_length
cut_word_list.reverse()
words = "/".join(cut_word_list)
return words
end