Skip to main content
 首页 » 编程设计

python之Dataframe 对象中的拼写更正,Python

2024年11月01日12zhoujg

我需要创建一个函数来接收名为 new_data 的数据框类型对象(包含文本的列),并且我需要将这些词与我的引用进行比较。 我的引用资料 ref_data 由 2 列组成,其中一列包含拼写错误的单词(与 new_data 的形式相同),第二列包含其更正后的版本。

简单来说,我需要将new_data的每个单词与ref_data的第一列进行比较,如果匹配,则返回该单词对应的第二列的单词。

例如,如果 new_data 的单词与第 3 行的 ref_data 的单词匹配,则第 3 行第 2 列的单词将替换它。如果需要,将提供更多说明。这是我尝试过的:

我试过这个:

x = [line for line in ref_data['word']] #x is a list of all incorrect words 
y = [line for line in ref_data['final']] #y is a list of all correct words 
def replace_words(x): #function 
for line in x: #iterate over lines in list 
    for word in line.split(): #iterate over words in list 
        if word == x:   #i dont know the syntax to compare with it.problem here 
           return (word = y)  #i need to return y of the same index.       

请您参考如下方法:

方法replace对此有好处。不要将不正确/正确的映射放入 DataFrame 的两列中,而是使用系列。

corrections = Series(correct_spellings, index=incorrect_spellings) 
new_data_corrected = new_data.replace(corrections) 

这是一个简单的例子。为简单起见,我使用字母;当然,它也适用于文字。

In [10]: new_data 
Out[10]:  
0    a 
1    b 
2    c 
dtype: object 
 
In [11]: corrections 
Out[11]:  
c    C 
b    B 
dtype: object 
 
In [12]: new_data.replace(corrections) 
Out[12]:  
0    a 
1    B 
2    C 
dtype: object