标签:基于 表示 name 概率 代码 raw 实现 else 统计
#使用正向最大匹配算法实现中文分词
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()
标签:基于 表示 name 概率 代码 raw 实现 else 统计
原文地址:https://www.cnblogs.com/yangzilaing/p/14616517.html