1

我有一组参考词(拼写正确),我需要输入一个用户输入词。使用levenshtein距离将输入词与参考列表进行比较,我需要从参考列表中返回具有最低成本的词。此外,该参考列表按频率排序,因此较高的频率出现在顶部。如果2个字的距离相同,则返回频率更高的字。 “NWORDS”是我根据频率排序的参考列表。 “候选人”是用户输入的单词。Levenshtein Python中的距离循环

代码:

for word in NWORDS: #iterate over all words in ref 
    i = jf.levenshtein_distance(candidate,word) #compute distance for each word with user input 

     #dont know what to do here 
    return word #function returns word from ref list with lowest dist and highest frequency of occurrence. 
+2

编辑距离是不是解决这个问题的办法。 http://norvig.com/spell-correct.html –

+0

另请参阅此问题:http://stackoverflow.com/questions/2294915/what-algorithm-gives-suggestions-in-a-spell-checker – Krumelur

+0

这只是整个问题的一部分。在此之前,我已经实施了peter norvig,但是我需要使用levenshtein提高效率。而且我的数据包含很少的英文单词。 –

回答

2

你可以接近这个如下:

match = None # best match word so far 
dist = None # best match distance so far 
for word in NWORDS: #iterate over all words in ref 
    i = jf.levenshtein_distance(candidate, word) #compute distance for each word with user input 
    if dist is None or i < dist: # or <= if lowest freq. first in NWORDS 
     match, dist = word, i 
return match #function returns word from ref list with lowest dist and highest frequency of occurrence