[英]string manipulation with python pandas and replacement function
我正在尝试编写一个代码来检查 csv 文件中的句子并搜索从第二个 csv 文件中给出的单词并替换它们,我的代码如下所示,它不会返回任何错误,但不会替换出于某种原因的任何单词,并在没有和替换的情况下打印回相同的句子。
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.