【问题标题】:How to correct words in panda dataframe?如何更正熊猫数据框中的单词?
【发布时间】:2021-08-21 07:16:37
【问题描述】:

我正在尝试纠正包含句子的 CSV 文件中的拼写错误。

input_csv:

id  text
0   my telephon not working
1   I have mobil in my bag
2   car is expensiv

here 提供的代码使用附魔通过提供建议来更正单词:

我想使用这种拼写纠正方法来纠正熊猫数据框中的单词。我有以下代码,首先对每个句子进行标记,然后检查拼写并提出最佳建议:

import enchant, difflib, nltk
from nltk.tokenize import word_tokenize
import pandas as pd

text = "telephon mobil" # This is only a sample
token = word_tokenize(text)

for word in token:
    best_words = []
    best_ratio = 0
    a = set(d.suggest(word))
    for b in a:
        tmp = difflib.SequenceMatcher(None, word, b).ratio()
        if tmp > best_ratio:
            best_words = [b]
            best_ratio = tmp
        elif tmp == best_ratio:
            best_words.append(b)
    print('word:[', word, '] -> best suggest:[', best_words[0],']')

word:[ telephon ] -> best suggest:[ telephone ]
word:[ mobil ] -> best suggest:[ mobile ]

现在我的问题是,如何将它应用到我的 panda 数据框并更正每一行中的拼写错误,并得到如下输出:

output_csv:

id  text
0   my telephone not working
1   I have mobile in my bag
2   car is expensive

【问题讨论】:

  • 试着把它变成一个函数并使用pd.Series.apply在每个单元格上运行函数
  • @MichaelDelgado 感谢您的评论。你能用代码示例展示一下吗?

标签: python pandas


【解决方案1】:

将您的代码放入一个函数中,然后使用apply 在每一行上调用它:

def word_suggest(word):
    d = enchant.Dict("en_US")
    if d.check(word):
        return word
    best_words = []
    best_ratio = 0
    a = set(d.suggest(word))
    for b in a:
        tmp = difflib.SequenceMatcher(None, word, b).ratio()
        if tmp > best_ratio:
            best_words = [b]
            best_ratio = tmp
        elif tmp == best_ratio:
            best_words.append(b)
    return best_words[0]

>>> df["text"].apply(lambda x: " ".join(word_suggest(word) for word in word_tokenize(x)))
0    my telephone not working
1     I have mobile in my bag
2            car is expensive
Name: text, dtype: object

【讨论】:

    猜你喜欢
    • 2017-01-11
    • 2019-12-31
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    相关资源
    最近更新 更多