2 回答
TA贡献1735条经验 获得超5个赞
您可以从中捕获单词,words并在替换中使用后向引用将其包装在*:
import re
import pandas as pd
df = pd.DataFrame([['I like apple pie','apple'],['Nice banana and lemon','banana|lemon']], columns=['text','words'])
df['text'] = df['text'].replace(r'('+df['words']+')', r'*\1*', regex=True)
print(df)
印刷:
text words
0 I like *apple* pie apple
1 Nice *banana* and *lemon* banana|lemon
TA贡献1805条经验 获得超9个赞
IIUC使用 (?i)与re.I
df.text.replace(regex=r'(?i)'+ df.words,value="*")
Out[131]:
0 I like * pie
1 Nice * and *
Name: text, dtype: object
由于您更新了问题
df.words=df.words.str.split('|')
s=df.words.apply(pd.Series).stack()
df.text.replace(dict(zip(s,'*'+s+'*')),regex=True)
Out[139]:
0 I like *apple* pie
1 Nice *banana* and *lemon*
Name: text, dtype: object
添加回答
举报