【问题标题】:Spell Checker for PythonPython 拼写检查器
【发布时间】:2012-12-05 08:59:58
【问题描述】:

我对 Python 和 NLTK 还很陌生。我正忙于一个可以执行拼写检查的应用程序(用正确的单词替换拼写错误的单词)。 我目前在 Python 2.7、PyEnchant 和 NLTK 库上使用 Enchant 库。下面的代码是一个处理更正/替换的类。

from nltk.metrics import edit_distance

class SpellingReplacer:
    def __init__(self, dict_name='en_GB', max_dist=2):
        self.spell_dict = enchant.Dict(dict_name)
        self.max_dist = 2

    def replace(self, word):
        if self.spell_dict.check(word):
            return word
        suggestions = self.spell_dict.suggest(word)

        if suggestions and edit_distance(word, suggestions[0]) <= self.max_dist:
            return suggestions[0]
        else:
            return word

我编写了一个函数,它接收一个单词列表并对每个单词执行 replace(),然后返回这些单词的列表,但拼写正确。

def spell_check(word_list):
    checked_list = []
    for item in word_list:
        replacer = SpellingReplacer()
        r = replacer.replace(item)
        checked_list.append(r)
    return checked_list

>>> word_list = ['car', 'colour']
>>> spell_check(words)
['car', 'color']

现在,我不太喜欢这个,因为它不是很准确,我正在寻找一种方法来实现单词的拼写检查和替换。我还需要一些可以识别诸如“caaaar”之类的拼写错误的东西?有没有更好的方法来执行拼写检查?如果是这样,它们是什么?谷歌是如何做到的?因为他们的拼写建议非常好。

有什么建议吗?

【问题讨论】:

    标签: python python-2.7 nltk spell-checking pyenchant


    【解决方案1】:

    您可以使用 autocorrect 库在 python 中进行拼写检查。
    示例用法:

    from autocorrect import Speller
    
    spell = Speller(lang='en')
    
    print(spell('caaaar'))
    print(spell('mussage'))
    print(spell('survice'))
    print(spell('hte'))
    

    结果:

    caesar
    message
    service
    the
    

    【讨论】:

    • print(spell('Stanger things')) 给 Stenger 东西
    • 这似乎不符合 Python-3 标准? spell = Speller(lang='en') 抛出 TypeError: the JSON object must be str, not 'bytes'
    • 不幸的是,这个库不值得信赖。在 100 个相对常见的词中,其中 6 个被自动更正为另一个词:sardine -> marine,stewardess ->stewards, snob -> snow, crutch ->clutch, pelt -> feel, toaster ->coaster
    • 哪个更好 pyspellchecler 或 autocorrect
    【解决方案2】:

    我建议先仔细阅读this post by Peter Norvig。 (我不得不做类似的事情,我发现它非常有用。)

    以下功能,特别是您现在需要使拼写检查器更复杂的想法:拆分、删除、转置和插入不规则单词以“纠正”它们。

    def edits1(word):
       splits     = [(word[:i], word[i:]) for i in range(len(word) + 1)]
       deletes    = [a + b[1:] for a, b in splits if b]
       transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
       replaces   = [a + c + b[1:] for a, b in splits for c in alphabet if b]
       inserts    = [a + c + b     for a, b in splits for c in alphabet]
       return set(deletes + transposes + replaces + inserts)
    

    注意:以上是来自 Norvig 的拼写校正器的一个 sn-p

    好消息是您可以逐步添加并不断改进您的拼写检查器。

    希望对您有所帮助。

    【讨论】:

    • Here 是一个开源、独立于语言、可训练的拼写检查器,其性能优于 Norvig 的方法,并且支持多种编码语言。
    【解决方案3】:

    在 python 中进行拼写检查的最佳方法是:SymSpell、Bk-Tree 或 Peter Novig 的方法。

    最快的是 SymSpell。

    这是Method1:参考链接pyspellchecker

    这个库基于 Peter Norvig 的实现。

    pip install pyspellchecker

    from spellchecker import SpellChecker
    
    spell = SpellChecker()
    
    # find those words that may be misspelled
    misspelled = spell.unknown(['something', 'is', 'hapenning', 'here'])
    
    for word in misspelled:
        # Get the one `most likely` answer
        print(spell.correction(word))
    
        # Get a list of `likely` options
        print(spell.candidates(word))
    

    方法二:SymSpell Python

    pip install -U symspellpy

    【讨论】:

    • 至少对于 python3,不推荐使用索引器,它目前破坏了 pyspellchecker 模块
    • pyspellchecker 非常慢并且会去除标点符号(但在 python 3.6 上可以)
    【解决方案4】:

    也许为时已晚,但我正在回答未来的搜索。 要执行拼写错误更正,您首先需要确保该词不是荒谬的或来自俚语,如 caaaar、amazzzing 等重复字母。所以,我们首先需要摆脱这些字母。正如我们所知,英语单词通常最多有 2 个重复的字母,例如 hello.,所以我们首先从单词中删除多余的重复,然后检查它们的拼写。 为了去除多余的字母,您可以使用 Python 中的正则表达式模块。

    完成后,使用 Python 中的 Pyspellchecker 库来纠正拼写。

    如需实施,请访问此链接:https://rustyonrampage.github.io/text-mining/2017/11/28/spelling-correction-with-python-and-nltk.html

    【讨论】:

    • 删除重复超过 2 个 lettters 的单词不是一个好主意。 (哦,我只是拼错了letters)。
    • 我没有说要删除整个单词,我描述的是从单词中删除多余的字母。所以,letttersletters。请仔细阅读答案。
    【解决方案5】:

    试试jamspell - 它非常适合自动拼写纠正:

    import jamspell
    
    corrector = jamspell.TSpellCorrector()
    corrector.LoadLangModel('en.bin')
    
    corrector.FixFragment('Some sentnec with error')
    # u'Some sentence with error'
    
    corrector.GetCandidates(['Some', 'sentnec', 'with', 'error'], 1)
    # ('sentence', 'senate', 'scented', 'sentinel')
    

    【讨论】:

      【解决方案6】:

      在终端

      pip install gingerit
      

      为了代码

      from gingerit.gingerit import GingerIt
      text = input("Enter text to be corrected")
      result = GingerIt().parse(text)
      corrections = result['corrections']
      correctText = result['result']
      
      print("Correct Text:",correctText)
      print()
      print("CORRECTIONS")
      for d in corrections:
        print("________________")  
        print("Previous:",d['text'])  
        print("Correction:",d['correct'])   
        print("`Definiton`:",d['definition'])
       
      

      【讨论】:

        【解决方案7】:

        拼写校正->

        如果您存储在其他地方,则需要将语料库导入桌面更改代码中的路径,我还使用 tkinter 添加了一些图形,这只是为了解决非单词错误!!

        def min_edit_dist(word1,word2):
            len_1=len(word1)
            len_2=len(word2)
            x = [[0]*(len_2+1) for _ in range(len_1+1)]#the matrix whose last element ->edit distance
            for i in range(0,len_1+1):  
                #initialization of base case values
                x[i][0]=i
                for j in range(0,len_2+1):
                    x[0][j]=j
            for i in range (1,len_1+1):
                for j in range(1,len_2+1):
                    if word1[i-1]==word2[j-1]:
                        x[i][j] = x[i-1][j-1]
                    else :
                        x[i][j]= min(x[i][j-1],x[i-1][j],x[i-1][j-1])+1
            return x[i][j]
        from Tkinter import *
        
        
        def retrieve_text():
            global word1
            word1=(app_entry.get())
            path="C:\Documents and Settings\Owner\Desktop\Dictionary.txt"
            ffile=open(path,'r')
            lines=ffile.readlines()
            distance_list=[]
            print "Suggestions coming right up count till 10"
            for i in range(0,58109):
                dist=min_edit_dist(word1,lines[i])
                distance_list.append(dist)
            for j in range(0,58109):
                if distance_list[j]<=2:
                    print lines[j]
                    print" "   
            ffile.close()
        if __name__ == "__main__":
            app_win = Tk()
            app_win.title("spell")
            app_label = Label(app_win, text="Enter the incorrect word")
            app_label.pack()
            app_entry = Entry(app_win)
            app_entry.pack()
            app_button = Button(app_win, text="Get Suggestions", command=retrieve_text)
            app_button.pack()
            # Initialize GUI loop
            app_win.mainloop()
        

        【讨论】:

          【解决方案8】:

          Spark NLP 是我使用的另一个选项,它运行良好。一个简单的教程可以在这里找到。 https://github.com/JohnSnowLabs/spark-nlp-workshop/blob/master/jupyter/annotation/english/spell-check-ml-pipeline/Pretrained-SpellCheckML-Pipeline.ipynb

          【讨论】:

            【解决方案9】:

            pyspellchecker 是解决此问题的最佳解决方案之一。 pyspellchecker 库基于 Peter Norvig’s 博客文章。 它使用Levenshtein Distance 算法在距离原始单词 2 的编辑距离内查找排列。 有两种方法可以安装这个库。官方文档强烈推荐使用pipev包。

            • 使用pip安装
            pip install pyspellchecker
            
            • 从源安装
            git clone https://github.com/barrust/pyspellchecker.git
            cd pyspellchecker
            python setup.py install
            

            以下代码是文档中提供的示例

            from spellchecker import SpellChecker
            
            spell = SpellChecker()
            
            # find those words that may be misspelled
            misspelled = spell.unknown(['something', 'is', 'hapenning', 'here'])
            
            for word in misspelled:
                # Get the one `most likely` answer
                print(spell.correction(word))
            
                # Get a list of `likely` options
                print(spell.candidates(word))
            

            【讨论】:

              【解决方案10】:

              from autocorrect import spell 为此,您需要安装,更喜欢 anaconda,它仅适用于单词,而不适用于句子,所以这是您将面临的限制。

              from autocorrect import spell
              print(spell('intrerpreter'))
              # output: interpreter
              

              【讨论】:

                【解决方案11】:

                你也可以试试:

                pip install textblob

                from textblob import TextBlob
                txt="machne learnig"
                b = TextBlob(txt)
                print("after spell correction: "+str(b.correct()))
                

                拼写纠正后:机器学习

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2013-07-03
                  • 1970-01-01
                  • 2012-07-29
                  • 1970-01-01
                  • 1970-01-01
                  • 2022-08-22
                  相关资源
                  最近更新 更多