我在http://norvig.com/spell-correct.html上尝试了拼写检查器的peter norvig代码 但我如何修改它以获得更多的建议而不只是1个正确的拼写
import re
from collections import Counter
def words(text):
return re.findall(r'\w+', text.lower())
WORDS = Counter(words(open('big.txt').read()))
def P(word, N=sum(WORDS.values())):
"Probability of `word`."
return WORDS[word] / N
def correction(word):
"Most probable spelling correction for word."
return max(candidates(word), key=P)
def candidates(word):
"Generate possible spelling corrections for word."
return (known([word]) or known(edits1(word)) or known(edits2(word)) or
[word])
def known(words):
"The subset of `words` that appear in the dictionary of WORDS."
return set(w for w in words if w in WORDS)
def edits1(word):
"All edits that are one edit away from `word`."
letters = 'abcdefghijklmnopqrstuvwxyz'
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
replaces = [L + c + R[1:] for L, R in splits if R for c in
letters]
inserts = [L + c + R for L, R in splits for c in
letters]
return set(deletes + transposes + replaces + inserts)
def edits2(word):
"All edits that are two edits away from `word`."
return (e2 for e1 in edits1(word) for e2 in edits1(e1))import re
答案 0 :(得分:0)
您可以使用candidates
功能。
它给你
如果在案例2或3中找到候选人,则返回的集合可能包含多个建议。
但是,如果原始单词被返回,则您不知道是否是这种情况,因为它是正确的(案例1),或者因为没有紧密的候选人(案例4)。
这种方法(实现edits1()
的方式)是强力的,对于长词来说效率非常低,如果你添加更多的字符(例如支持其他语言),它会变得更糟。考虑类似simstring之类的内容,以便有效地检索大型集合中具有相似拼写的单词。