0

我正在尝试编写一个拼写检查器,我想使用 difflib 来实现它。基本上,我有一个技术术语列表,我添加到标准 unix 字典 ( /usr/share/dict/words) 中,并将其存储在一个名为 dictionaryFile.py 的文件中。

我有另一个名为 stringSim.py 的脚本,我在其中导入字典并针对它测试示例字符串。这是基本代码:

import os, sys
import difflib
import time
from dictionaryFile import wordList

inputString = "dictiunary" 
print "Search query: "+inputString  
startTime = time.time()

inputStringSplit = inputString.split()
for term in inputStringSplit:
termL = term.lower()
print "Search term: "+term
closeMatches = difflib.get_close_matches(termL,wordList)
if closeMatches[0] == termL: 
    print "Perfect Match"
else:
    print "Possible Matches"
    print "\n".join(closeMatches)

print time.time() - startTime, "seconds"

它返回以下内容:

$ python stringSim.py 
Search query: dictiunary
Search term: dictiunary
Possible Matches
dictionary
dictionary's
discretionary
0.492614984512 seconds

我想知道是否有更好的策略可以用来查找类似的匹配项(假设单词拼写错误)。这是针对 Web 应用程序的,因此我正在尝试优化这部分代码,使其更加简洁。有没有更好的方法可以构造 wordList 变量(现在它只是一个单词列表)?

谢谢。

4

1 回答 1

0

I'm not sure difflib is best solution for this kind of work; typically, spellcheckers use some sort of edit distance, e.g. Levenshtein distance. NLTK includes implementation(s) of edit distance, I'd start there instead.

于 2014-05-16T19:49:41.973 回答