如何修改 peter norvig 拼写检查器以获得每个单词的更多建议

how to modify peter norvig spell checker to get more number of suggestions per word

我在 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

您可以使用candidates函数。

它给你

  • 原来的单词如果已经正确了
  • 否则,与原词编辑距离为1的所有已知词
  • 如果没有距离为1的候选,则所有距离为2的候选
  • 如果前面的case都没有,那么就是原话

如果在情况 2 或 3 中找到候选者,则返回的集合可能包含多个建议。

但是,如果返回原始单词,您不知道是因为它是正确的(情况 1)还是因为没有接近的候选词(情况 4)。

然而,

这种方法(edits1() 的实现方式)是蛮力的,对于长单词来说效率很低,如果添加更多字符(例如,为了支持其他语言),情况会变得更糟。考虑类似 simstring 的东西,以便在大型集合中有效地检索具有相似拼写的单词。