python实现查询纠错

python实现查询纠错的方法:
方法一:
1、输入拼写错误的单词,调用 aspell -a 然后得到一些正确的单词,然后用距离编辑进一步选择更准确的单词。例如,操作 aspell -a,输入 ‘hella’ 得到以下结果:
hell, Helli, hello, heal, Heall, he’ll, hells, Heller, Ella, Hall, Hill, Hull, hall, heel, hill, hula, hull, Helga, Helsa, Bella, Della, Mella, Sella, fella, Halli, Hally, Hilly, Holli, Holly, hallo, hilly, holly, hullo, Hell’s, hell’s
2、距离编辑是什么?(Edit-Distance,也叫 Levenshtein algorithm)那呢?也就是说,给定一个单词,通过多次插入、删除、交换和替换单字符,列出所有可能的正确拼写,如输入 ‘hella经过多次插入、删除、交换、替换单字符的操作,变成:
‘helkla’, ‘hjlla’, ‘hylla’, ‘hellma’, ‘khella’, ‘iella’, ‘helhla’, ‘hellag’, ‘hela’, ‘vhella’, ‘hhella’, ‘hell’, ‘heglla’, ‘hvlla’, ‘hellaa’, ‘ghella’, ‘hellar’, ‘heslla’, ‘lhella’, ‘helpa’, ‘hello’, …
3、综合以上两集的结果,考虑到一些理论知识可以提高拼写检查的准确性,例如,一般来说,错误的单词是无意的或错误的,完全错误的单词的可能性很小,单词的第一个字母通常不会拼写错误。因此,您可以删除上述集合中的第一个字母不一致的单词,例如:‘Sella’, ‘Mella’, khella’, ‘iella’ 等,这里 VPSee 在不删除单词的情况下,将这些单词从队列中取出,放在队列的末尾(优先级降低),因此无法匹配它们 h 开头的单词与其他字母开头的单词相匹配。
4、外部工具在程序中使用 aspell,如何在 Python 在内部捕获外部程序的输入和输出 Python 在程序中处理这些输入和输出?Python 2.4 以后引入了 subprocess 可以使用的模块 subprocess.Popen 来处理。
实现代码:
#!/usr/bin/python
#Asimplespellchecker
importos,sys,subprocess,signal
alphabet='abcdefghijklmnopqrstuvwxyz'
deffound(word,args,cwd=None,shell=True):
child=subprocess.Popen(args,
shell=shell,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
cwd=cwd,
universal_newlines=True)
child.stdout.readline()
(stdout,stderr)=child.communicate(word)
if":"instdout:
#remove\n\n
stdout=stdout.rstrip("\n")
#removeleftpartuntil:
left,candidates=stdout.split(":",1)
candidates=candidates.split(",")
#makinganerroronthefirstletterofawordisless
#probable,soweremovethosecandidatesandappendthem
#tothetailofqueue,makethemlesspriority
foritemincandidates:
ifitem[0]!=word[0]:
candidates.remove(item)
candidates.append(item)
returncandidates
else:
returnNone
#copyfromhttp://norvig.com/spell-correct.html
defedits1(word):
n=len(word)
returnset([word[0:i]+word[i+1:]foriinrange(n)]+
[word[0:i]+word[i+1]+word[i]+word[i+2:]foriinrange(n-1)]+
[word[0:i]+c+word[i+1:]foriinrange(n)forcinalphabet]+
[word[0:i]+c+word[i:]foriinrange(n+1)forcinalphabet])
defcorrect(word):
candidates1=found(word,'aspell-a')
ifnotcandidates1:
print"nosuggestion"
return
candidates2=edits1(word)
candidates=[]forwordincandidates1:
ifwordincandidates2:
candidates.append(word)
ifnotcandidates:
print"suggestion:%s"%candidates1[0]else:
print"suggestion:%s"%max(candidates)
defsignal_handler(signal,frame):
sys.exit(0)
if__name__='__main__':
signal.signal(signal.SIGINT,signal_handler)
whileTrue:
input=raw_input()
correct(input)方法二:
当然,直接在程序中调用相关模块是最简单的。有一个叫做 PyEnchant 图书馆支持拼写检查和安装 PyEnchant 和 Enchant 之后可以直接在那里 Python 程序里 import 了:
>>>importenchant
>>>d=enchant.Dict("en_US")
>>>d.check("Hello")
True
>>>d.check("Helo")
False
>>>d.suggest("Helo")
['Helo','He-lo','Hello','Helot','Help','Halo','Hell','Held','Helm','Hero',"He'll"]
>>>请关注Python视频教程栏目,了解更多Python知识。
