首页 > 解决方案 > 如何在 Python 中有效地对大型文本语料库使用拼写校正

问题描述

考虑以下拼写纠正:

from autocorrect import spell
import re

WORD = re.compile(r'\w+')
def reTokenize(doc):
    tokens = WORD.findall(doc)
    return tokens

text = ["Hi, welcmoe to speling.","This is jsut an exapmle, but cosnider a veri big coprus."]
def spell_correct(text):
    sptext = []
    for doc in text:
        sptext.append(' '.join([spell(w).lower() for w in reTokenize(doc)]))      
    return sptext    

print(spell_correct(text)) 

这是上述代码的输出:

在此处输入图像描述

如何停止在 jupyter notebook 中显示输出?特别是如果我们有大量的文本文档,就会有很多输出。

我的第二个问题是:在大数据上应用时,如何提高代码的速度和准确性(例如,请检查输出中的“veri”一词)?有没有更好的方法来做到这一点?感谢您以更快的速度响应和(替代)解决方案。

标签: pythontext-processingspell-checkingspelling

解决方案


正如@khelwood 在评论中所说,您应该使用autocorrect.Speller

from autocorrect import Speller
import re


spell=Speller(lang="en")
WORD = re.compile(r'\w+')
def reTokenize(doc):
    tokens = WORD.findall(doc)
    return tokens

text = ["Hi, welcmoe to speling.","This is jsut an exapmle, but cosnider a veri big coprus."]
def spell_correct(text):
    sptext = []
    for doc in text:
        sptext.append(' '.join([spell(w).lower() for w in reTokenize(doc)]))      
    return sptext    

print(spell_correct(text)) 

#Output
#['hi welcome to spelling', 'this is just an example but consider a veri big corpus']

作为替代方案,您可以使用列表推导来提高速度,也可以使用 library ,在这种情况下pyspellchecker提高单词的准确性:'veri'

from spellchecker import SpellChecker
import re

WORD = re.compile(r'\w+')
spell = SpellChecker()

def reTokenize(doc):
    tokens = WORD.findall(doc)
    return tokens

text = ["Hi, welcmoe to speling.","This is jsut an exapmle, but cosnider a veri big coprus."]

def spell_correct(text):
    sptext =  [' '.join([spell.correction(w).lower() for w in reTokenize(doc)])  for doc in text]    
    return sptext    

print(spell_correct(text)) 

输出:

['hi welcome to spelling', 'this is just an example but consider a very big corpus']

推荐阅读