完整资料和代码获取地址github:zlhcsm
知识普及-正向最大匹配法:
对于输入的一段文本从左至右、以贪心的方式切分出当前位置上长度最大的词。
正向最大匹配算法是基于词典的分词方法,其分词原理是:单词的颗粒度越大,所能表示的含义越确切。
步骤
1,一般从一个字符串的开始位置,选择一个最大长度的词长的片段,如果序列不足最大词长,则选择全部序列。
2,首先看该片段是否在词典中,如果是,则算为一个分出来的词,如果不是,则从右边开始,减少一个字符,然后看短一点的这个片段是否在词典中,一次循环,直到只剩下一个字。
3,序列变为第2步骤截取分词后,剩下的部分序列
核心代码
1.读取字典文件
def init():
"""
读取字典文件
载入词典
:return:
"""
with open("../dic/dict.txt", "r", encoding="utf8") as dict_input:
for word in dict_input:
# 文件格式为:单词 词频 词性
words_dic.append(word.split(" ")[0].strip())
2.切词方法
# 实现正向匹配算法中的切词方法
def cut_words(raw_sentence, word_dic):
# 统计词典中最长的词
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)
sub_sen = sentence[0:max_cut_length]
while max_cut_length > 0:
if sub_sen in word_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[0:max_cut_length]
sentence = sentence[max_cut_length:]
word_length = word_length - max_cut_length
words = '/'.join(cut_word_list)
return words
end
来源:CSDN
作者:自由的小白
链接:https://blog.csdn.net/zzzzlei123123123/article/details/104043794