首页 > 解决方案 > 在 Python 中的字符串系列中替换不正确单词的有效方法

问题描述

我正在处理手写的文本数据,所以它有很多拼写错误。我目前正在清理数据,并且当单词不存在时pyspellchecker,我正在使用该方法查找最可能的单词。correct()我的方法是创建一个字典,其中所有写得不好的单词作为键,最有可能的单词作为值:

dic={}
for i in df.text:
    misspelled = spell.unknown(i.split())
    for word in misspelled:
        dic[word]=spell.correction(word)

尽管这是有效的,但它的速度非常缓慢。因此,我想知道是否有更快的选择来实现这一点。你有什么想法?

编辑:df.text 中有 10571 行,字符串通常有 5-15 个字长。每个循环大约需要 3-5 秒,这使得运行整个循环总共需要大约 40000 秒。

标签: pythonpandasnlp

解决方案


如果您只想创建一个从您遇到的拼写错误的单词到他们的建议的映射,您可以通过删除重复的单词来减小数据集的大小。spell.unknown这将最大限度地减少对and的调用次数,spell.correction并防止对字典内容进行不必要的更新。

uniquewords = set().union(*(sentence.split() for sentence in df.text))
corrections = {word: spell.correction(word) for word in spell.unknown(uniquewords)}

推荐阅读