【问题标题】:how to modify peter norvig spell checker to get more number of suggestions per word如何修改 peter norvig 拼写检查器以获得更多每个单词的建议
【发布时间】:2017-04-14 11:08:31
【问题描述】:

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

【问题讨论】:

    标签: python nlp nltk spell-checking


    【解决方案1】:

    您可以使用candidates 函数。

    它给你

    • 如果原词已经正确,则为原词
    • 否则,与原始单词编辑距离为 1 的所有已知单词
    • 如果没有距离为 1 的候选者,则所有距离为 2 的候选者
    • 如果前一种情况没有,则原词

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

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

    然而,

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

    【讨论】:

    • >>> 导入 simstring >>> db = simstring.reader('web1tuni/web1tuni.db') >>> db.measure = simstring.cosine >>> db.threshold = 0.9 >> > db.retrieve('近似')('近似','近似','近似','近似','近似','近似近似','近似','近似','近似','近似' , 'reapproximate', 'toapproximate') 为什么它会根据字典显示这些不正确的词
    • 因为 web1tuni 不是字典,而是网上找到的单词集合。我不确定为什么它包含二元组,顾名思义它应该只包含一元组。
    • 有没有我可以避免那些错误的单词建议?我在文本文件中尝试了许多英文单词,但其中许多单词都有错误。在使用 pyenchant 库时,我使用了官方给出的 en_US 字典,但它仍然为 helo 提供了一些错误的建议,例如 'he lo' ['helo'] ['hole', 'hello', 'helot', 'halo', ' hero', 'hell', 'held', 'helm', 'help', 'he lo'] ['grp'] ['gr', 'gorp', 'grip', 'gap', 'gyp', 'gr p']
    • 如果您接受“gr”作为缩写(以及单个字母),那么您列出的每个建议都是正确的英文单词(如果您不相信,请在 dictionary 中查找它们我)。如果您想找到最可能的候选者,例如,您可以考虑 unigram(或 n-gram)频率。
    猜你喜欢
    • 2017-06-18
    • 2017-11-06
    • 2018-01-09
    • 1970-01-01
    • 2015-01-21
    • 2019-04-11
    • 2011-05-11
    • 2013-05-25
    相关资源
    最近更新 更多