使用 python pandas 和替换函数进行字符串操作

string manipulation with python pandas and replacement function

我正在尝试编写一个代码来检查 csv 文件中的句子并搜索第二个 csv 文件中给出的单词并替换它们,我的代码如下所示 return 任何错误,但由于某些原因它不会替换任何单词并打印回相同的句子而无需替换。


import string
import pandas as pd
text=pd.read_csv("sentences.csv")
change=pd.read_csv("replace.csv")
for row in text:
    print(text.replace(change['word'],change['replacement']))

句子 csv 文件看起来像

更改后的 csv 文件看起来像

尝试:

text=pd.read_csv("sentences.csv")
change=pd.read_csv("replace.csv")
toupdate = dict(zip(change.word, change.replacement))
text = text['sentences'].replace(toupdate, regex=True)
print(text)

dataframe.replace(x,y) 将完整的 x 更改为 y,而不是 x 的一部分。

您必须使用正则表达式或自定义函数来执行您想要的操作。例如:

change_dict = dict(zip(change.word,change.replacement))
def replace_word(txt):
    for key,val in change_dict.items():
        txt = txt.replace(key,val)
return txt
print(text['sentences'].apply(replace_word))

// 再创建一列以避免对原始列进行任何更改

text["new_sentence"]=text["sentences"]

for changeInd in change.index:
    for eachTextid in text.index:
        text["new_sentence"][eachTextid]=text["new_sentence"][eachTextid].replace(change['word'][changeInd],change['replacement'][changeInd])

clear code: click here plz