我有一个包含近 4,000 个不同字符串的系列,以及一个包含两个系列的数据框。我试图迭代每个字符串,找到这些字符串中与其他数据帧的第二个系列中的任何单词匹配的单词。如果它们匹配,则将系列中字符串中的单词替换为数据框中第一个系列中的单词。
这是我正在尝试做的事情的示例。
拆分为列表的示例字符串。
0 [I, like, the, acura, vigor]
数据框。
acura integra
0 acura legend
1 acura vigor
2 acura rlx
3 acura ilx
4 acura mdx
因此,该字符串会将“vigor”替换为“acura”。
[I, like, the, acura, acura]
最佳答案
实际上,数据帧方法似乎有点过度设计。 我建议使用简单的正则表达式:
import re
txt = 'this is a test text to replace legend, 2nd legend and fox with acura'
wordlist = ['fox', 'legend']
for word in wordlist:
txt = re.sub(word,'acura',txt)
print(txt)
如果您需要数据帧来执行进一步的步骤,您仍然可以使用正则表达式示例作为基础。
关于python - 如果字符串中的单词与单独系列中的单词匹配,则替换它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63853016/