我正在尝试编写一个拼写检查器,我想使用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搜索查询:字典搜索词:字典可能匹配字典的任意0.492614984512秒
我想知道是否有更好的策略可以用来查找类似的匹配(假设一个单词拼错了)。这是一个web应用程序,所以我试图优化这部分代码,使之更快。有没有更好的方法来构造wordList变量(现在它只是一个单词列表)?
发布于 2014-05-16 19:05:15
使用difflib可能是最好的选择。所以问题在于你的单词列表的大小。如果我们能够减少difflib需要比较的单词数,那么我们就可以得到一个更快的时间。
要实现的一个想法是,只使用接近-足够长的单词:
# Returns the min and max thresholds for word length
def get_thresholds(word, min=3, max=3):
length = len(word)
return max(1, length-min), length+max
# Returns only words whose length is within a certain range
def filter_word_list(min, max):
return [word for word in words_list if min <= len(word) <= max]因此,对get_close_matches()的调用应该是:
closeMatches = difflib.get_close_matches(termL,
dictionaryFile.filter_word_list(*get_thresholds(termL)))另一个想法是过滤以字母开头的单词,该字母在空间上与键盘上的第一个字母相关。然而,由于不同的键盘布局,这一建议并不那么可信。
作为一些一般性意见:
underscores_between_words而不是camelCaseNames。MyModule而不是myModule。另外,每个不同的模块导入都有自己的行:# Not import os, sys导入os导入系统https://codereview.stackexchange.com/questions/50947
复制相似问题