python 替换单词而不是子字符串

python replace word not substring

我想用数据框列中的另一个词替换一个词。这是我的 python 代码:

import pandas as pd
text="age engage"
df=pd.DataFrame([x.split(';') for x in text.split('\n')])
df['text'] = df[0].str.replace(r"age","âge")

我在 Whosebug 上找到的代码(包括这个)允许我在想要获得 df['text']="âge engage" 时获得 df['text']="âge engâge"。谁能帮我改进我的代码?我的数据框中有几十个不同的词要替换,所以我想用一个简单的代码来实现不同的词。

尝试-

import pandas as pd
text="age engage"
df=pd.DataFrame([x.split(';') for x in text.split('\n')])
df['text'] = df[0].str.replace(r"^age","âge") # the carrot indicates to only match from the start of the line

结果

        0        text
0  age engage  âge engage 

您还可以查看正则表达式,这是一个在模式匹配方面可以玩转的好网站 Regex 101

我建议使用这样的方法:

import re

text = 'age engage'
for words in ['age']:
    if re.search(r'\b' + words + r'\b', text):
        print('{0}'.format(words).replace(r"age","âge"))

输出:

âge