数据帧中缩略语和拼错词的处理

2024-05-23 13:20:13 发布

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

我有一个数据框包含拼写错误的单词和缩写,就像这样。你知道吗

input:
df = pd.DataFrame(['swtch', 'cola', 'FBI', 
      'smsng', 'BCA', 'MIB'], columns=['misspelled'])

output:
       misspelled
0   swtch
1   cola
2   FBI
3   smsng
4   BCA
5   MIB

我需要纠正拼写错误的单词和缩写

我尝试过创建字典,例如:

input: 
dicts = pd.DataFrame(['coca cola', 'Federal Bureau of Investigation', 
                    'samsung', 'Bank Central Asia', 'switch', 'Men In Black'], columns=['words'])

output:
        words
0   coca cola
1   Federal Bureau of Investigation
2   samsung
3   Bank Central Asia
4   switch
5   Men In Black 

应用这个代码

x = [next(iter(x), np.nan) for x in map(lambda x: difflib.get_close_matches(x, dicts.words), df.misspelled)]
df['fix'] = x

print (df)

输出结果是我已成功更正拼写错误,但不是缩写

misspelled        fix
0      swtch     switch
1       cola  coca cola
2        FBI        NaN
3      smsng    samsung
4        BCA        NaN
5        MIB        NaN

请帮忙。你知道吗


Tags: dfnan单词mibwordsswitchfbi拼写错误
1条回答
网友
1楼 · 发布于 2024-05-23 13:20:13

不如采用双管齐下的方法,首先纠正拼写错误,然后扩展缩写:

df = pd.DataFrame(['swtch', 'cola', 'FBI', 'smsng', 'BCA', 'MIB'], columns=['misspelled'])
abbreviations = {
    'FBI': 'Federal Bureau of Investigation',
    'BCA': 'Bank Central Asia',
    'MIB': 'Men In Black',
    'cola': 'Coca Cola'
}

spell = SpellChecker()
df['fixed'] = df['misspelled'].apply(spell.correction).replace(abbreviations)

结果:

  misspelled                            fixed
0      swtch                           switch
1       cola                        Coca Cola
2        FBI  Federal Bureau of Investigation
3      smsng                            among
4        BCA                Bank Central Asia
5        MIB                     Men In Black

我使用^{},但你可以使用任何拼写检查库。它将smsng更正为among,但这是自动拼写更正的一个警告。不同的库可能给出不同的结果

相关问题 更多 >