如何使用enchant对pandas dataframe中的文本内容进行拼写纠错
基于Pandas实现CSV文本拼写纠错
需求说明
需要修正CSV文件中text字段的英文拼写错误,输入CSV格式如下:
id text 0 my telephon not working 1 I have mobil in my bag 2 car is expensiv
最终需要输出修正后的CSV,格式如下:
id text 0 my telephone not working 1 I have mobile in my bag 2 car is expensive
实现思路
将已有的单句拼写纠错逻辑封装为独立函数,通过Pandas的apply方法将函数应用到text列的每一行,实现批量纠错。
完整实现代码
import enchant, difflib, nltk from nltk.tokenize import word_tokenize import pandas as pd # 初始化英文拼写校验词典 d = enchant.Dict("en_US") # 定义单个单词纠错函数 def correct_single_word(word): # 单词拼写正确直接返回 if d.check(word): return word # 无拼写建议时直接返回原词 suggest_words = set(d.suggest(word)) if not suggest_words: return word # 匹配相似度最高的建议词 best_ratio = 0 best_words = [] for b in suggest_words: 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] # 定义整句纠错函数 def correct_sentence(text): tokens = word_tokenize(text) corrected_tokens = [correct_single_word(word) for word in tokens] return ' '.join(corrected_tokens) # 读取输入CSV,制表符分隔用sep='\t',逗号分隔可直接省略sep参数 df = pd.read_csv('你的输入文件路径.csv', sep='\t') # 对text列应用纠错逻辑 df['text'] = df['text'].apply(correct_sentence) # 输出结果CSV df.to_csv('修正后的输出文件路径.csv', sep='\t', index=False)
注意事项
- 运行前需要提前安装依赖:
pip install pyenchant nltk pandas,同时需要下载nltk的punkt分词数据包,可通过nltk.download('punkt')完成下载。 - 如果需要处理其他语言的拼写纠错,只需修改enchant初始化时的语言代码即可。
内容的提问来源于stack exchange,提问作者Bilgin
相关产品推荐
相关产品推荐

