首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用difflib查找单词字典

使用difflib查找单词字典
EN

Code Review用户
提问于 2014-05-16 18:04:45
回答 1查看 1.2K关注 0票数 4

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

我有另一个名为stringSim.py的脚本,在该脚本中导入字典并对其测试示例字符串:

代码语言:javascript
复制
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变量(现在它只是一个单词列表)?

EN

回答 1

Code Review用户

发布于 2014-05-16 19:05:15

使用difflib可能是最好的选择。所以问题在于你的单词列表的大小。如果我们能够减少difflib需要比较的单词数,那么我们就可以得到一个更快的时间。

要实现的一个想法是,只使用接近-足够长的单词:

代码语言:javascript
复制
# 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()的调用应该是:

代码语言:javascript
复制
closeMatches = difflib.get_close_matches(termL,
                       dictionaryFile.filter_word_list(*get_thresholds(termL)))

另一个想法是过滤以字母开头的单词,该字母在空间上与键盘上的第一个字母相关。然而,由于不同的键盘布局,这一建议并不那么可信。

作为一些一般性意见:

  1. 看看你的变量名。它们是描述性的(在大多数情况下),但是官方Python风格指南建议使用underscores_between_words而不是camelCaseNames
  2. 模块名称的基本概念相同。Pythonic模块名被写为MyModule而不是myModule。另外,每个不同的模块导入都有自己的行:# Not import os, sys导入os导入系统
票数 3
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/50947

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档