def viterbi_split_word(sentence,dictionaries):
math = __import__('math')
lenht_of_seq = len(sentence)
def directed_acyclic_graph(sentence):
DAG = {}
for end in range(lenht_of_seq):
tmp = []
start = end
point = sentence[end]
for start in range(start,lenht_of_seq):
if point in word_dict:
tmp.append(start)
point = sentence[end:start + 2]
if not tmp:
tmp.append(end)
DAG[end] = tmp
return DAG
route={}
route[lenht_of_seq] = (0, 0)
DAG = directed_acyclic_graph(sentence)
for reverse_start in range(lenht_of_seq - 1, -1, -1):
distance = (((word_dict.get(sentence[reverse_start:start + 1]) or 0) + route[start + 1][0], start) for start in DAG[reverse_start])
route[reverse_start] = max(distance)
start = 0
words = []
while start < lenht_of_seq:
init_start = route[start][1] + 1
word = sentence[start:init_start]
words.append(word)
start = init_start
return (sum(i[0]==0 and 10**(-8) or -math.log(i[0]) for i in route.values()),words,DAG)
viterbi_split_word(sentence ="我们经常有意见分歧,这是没有办法的意见分歧",dictionaries=word_dict)
维特比分词算法(纯循环)
最新推荐文章于 2022-03-05 11:54:17 发布