处理数据帧熊猫中的缩写和拼写错误的单词



我有一个数据帧包含拼写错误的单词和缩写,如下所示。

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

请帮忙。

如何遵循双管齐下的方法,首先纠正拼写错误,然后扩展缩写:

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

我使用pyspellchecker但您可以使用任何拼写检查库。它更正了smsngamong但这是自动拼写更正的警告。不同的库可能会给出不同的结果

最新更新