【问题标题】:How to correct spelling in a Pandas DataFrame如何更正 Pandas DataFrame 中的拼写
【发布时间】:2016-01-28 19:35:49
【问题描述】:

使用TextBlob 库,可以通过首先将字符串定义为TextBlob 对象然后使用correct 方法来改进字符串的拼写。

例子:

from textblob import TextBlob
data = TextBlob('Two raods diverrged in a yullow waod and surry I culd not travl bouth')
print (data.correct())
Two roads diverged in a yellow wood and sorry I could not travel both

是否可以对 Pandas DataFrame 系列中的字符串执行此操作,例如这个:

data = [{'one': '3', 'two': 'two raods'}, 
         {'one': '7', 'two': 'diverrged in a yullow'}, 
        {'one': '8', 'two': 'waod and surry I'}, 
        {'one': '9', 'two': 'culd not travl bouth'}]
df = pd.DataFrame(data)
df

    one   two
0   3     Two raods
1   7     diverrged in a yullow
2   8     waod and surry I
3   9     culd not travl bouth

要返回这个:

    one   two
0   3     Two roads
1   7     diverged in a yellow
2   8     wood and sorry I
3   9     could not travel both

使用 TextBlob 或其他方法。

【问题讨论】:

    标签: python pandas nlp textblob


    【解决方案1】:

    你可以这样做:

    df.two.apply(lambda txt: ''.join(textblob.TextBlob(txt).correct()))
    

    使用pandas.Series.apply

    【讨论】:

    • 好的,但如果我这样做,它会返回如下字符串:(T, w, o, , r, o, a, d, s)
    • @JRD 好的,请参阅更新 - 显然这个库返回元组,所以我只是 joined 他们。
    【解决方案2】:

    我仍在寻找更快的方法。但是,我认为 python 中有一个名为autocorrect 的不同库可以帮助进行拼写纠正。我在演示数据上对两个库(autocorrecttestblob)进行了计时,这就是我得到的结果。

    %%timeit
    spell_correct_tb(['haave', 'naame'])
    The slowest run took 4.36 times longer than the fastest. This could mean that an intermediate result is being cached.
    1000 loops, best of 3: 505 µs per loop
    
    %%timeit
    spell_correct_autocorrect(['haave', 'naame'])
    The slowest run took 4.80 times longer than the fastest. This could mean that an intermediate result is being cached.
    1000 loops, best of 3: 303 µs per loop
    

    这表明autocorrect 工作得更快(或者我的假设是否错误?)。但是,我不太确定这两个库的准确度。

    注意:您可以使用 pip 运行命令 pip install autocorrect 安装自动更正

    【讨论】:

    • 我使用了 TextBlobcorrect() 方法,我花了大约 31 分钟 来纠正 ~6500 个文档 .它不是 100% 准确,但我同意这是一项涉及高计算能力的任务。
    猜你喜欢
    • 2023-02-11
    • 2022-01-09
    • 2018-02-11
    • 2019-07-02
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多