Python:提高对文本数据执行拼写更正的代码性能

2024-06-25 22:36:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个以注释形式存在的文本数据,我想对其进行预处理。除了去除诸如URL、数字等噪音外。。。在进行柠檬化的同时,我还想进行拼写更正。具体来说,我只想对出现次数不超过给定次数的单词执行拼写更正,以避免误报。为此,我使用pyspellchecker进行校正,使用nltks FreqDist获得单词频率,但是,这样做会显著增加预处理所需的时间

我试着让事情尽我所能的表现,但我被卡住了,想知道是否还有改进的地方

这是我的密码: 进口:

from spacy.lang.en import English
from spellchecker import SpellChecker
from nltk.probability import FreqDist
nlp = spacy.load("en_core_web_sm")
spell = SpellChecker()
fdist = FreqDist()

代码:

dict_misspell = {}

pipe = nlp.pipe(list_of_comments, batch_size = 512 ,disable = ["tagger", "parser"])
    for j, doc in enumerate(pipe):
        tokens = [token.lemma_.lower() for token in doc if not token.is_punct and not token.is_digit\
                                  and not token.like_url and not token.like_email and not token.like_num]
        processed_comments.append(" ".join(tokens))
        fdist += FreqDist(tokens)
        
        #remember which comments contain missspellings to avoid having to look at every comment later
        misspelled = spell.unknown(tokens)
        if (len(misspelled) > 0):
            for misspelled_word in misspelled:
                if misspelled_word in dict_misspell.keys():
                    dict_misspell[misspelled_word].append(j)
                else:
                    dict_misspell[misspelled_word] = [j]
    
    #spell correction is done after the rest because only then is the frequency dict fully build.
    for k, mis in enumerate(dict_misspell.keys()):
        if(fdist[mis] <= 5):  #only fix below certain word frequency to avoid false positives
            missspelling_idxs = dict_misspell[mis]
            correct_spelling = spell.correction(mis)
            for idx in missspelling_idxs:
                processed_comments[idx] = processed_comments[idx].replace(mis, correct_spelling)

如上所述,我对每个注释进行预处理,将该注释的所有单词添加到频率词典中,对于拼写检查器认为拼写错误的每个单词,我将这些单词和注释索引保存在拼写错误词典中。这样做之后,频率字典就完全建立起来了,我开始纠正可能拼写错误的单词,这些单词的频率符合个人评论中的条件

有人看到了改进性能的方法吗


Tags: intokenfornot单词commentsdictword
1条回答
网友
1楼 · 发布于 2024-06-25 22:36:53

拼写检查是一个相当繁重的过程

您可以尝试过滤掉dict_拼写错误中的一些标记,以便在较少的单词上调用correction。您可以分析注释子集中的未知单词,并创建一些规则来过滤某种标记

示例:少于2个字符的单词;里面有数字的;表情符号;命名实体;…)

相关问题 更多 >