首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >替换字符串中的单词,如果它们与单独系列中的单词匹配

替换字符串中的单词,如果它们与单独系列中的单词匹配
EN

Stack Overflow用户
提问于 2020-09-12 03:12:43
回答 2查看 43关注 0票数 2

我有一个系列,它有近4000个不同的字符串,以及一个包含两个系列的数据帧。我试图遍历每个字符串,找到那些字符串中与其他数据帧的第二系列中的任何单词匹配的单词。如果它们匹配,则将字符串中的单词替换为数据帧中第一个序列中的单词。

这是我想要做的一个例子。

拆分成列表的示例字符串。

代码语言:javascript
复制
0    [I, like, the, acura, vigor]

数据框。

代码语言:javascript
复制
acura   integra
0   acura   legend
1   acura   vigor
2   acura   rlx
3   acura   ilx
4   acura   mdx

因此,该字符串将“vigor”替换为“acura”。

代码语言:javascript
复制
[I, like, the, acura, acura]
EN

回答 2

Stack Overflow用户

发布于 2020-09-12 05:05:14

实际上,数据帧方法似乎有点过度工程化。我建议使用简单的正则表达式:

代码语言:javascript
复制
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)

如果您需要进一步步骤的数据帧,您仍然可以使用正则表达式示例作为基础。

票数 1
EN

Stack Overflow用户

发布于 2020-09-12 06:43:02

让我们把这个问题分解一下。

  1. 你想要遍历列表。对于列表中的每个单词w
    1. 在数据帧中查找单词w
    2. 将列表中的该索引设置为dataframe.

中的相应替换

作为代码,

代码语言:javascript
复制
mylist = ['I', 'like', 'the', 'acura', 'vigor']
# df = the dataframe, with columns 'replacement' and 'lookup'
for index, word in enumerate(mylist):
    matched_row = df.loc[df['lookup'] == word]
    if not matched_row.empty:
        mylist[index] = matched_row.iloc[0]['replacement']
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63853016

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档