首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用regex替换单词列表

问用regex替换单词列表
EN

Stack Overflow用户
提问于 2021-05-27 17:48:30
回答 3查看 526关注 0票数 2

我有一个单词列表list_words =["cat","dog","animals"]

我有一个text = "I have a lot of animals a cat and a dog"

我想要一个regex代码,它能够在列表中的任何单词之前在每个单词的末尾添加一个逗号。

我希望我的短信是这样的:text = "I have a lot of, animals a, cat and a, dog"

到目前为止我的代码是:

代码语言:javascript
复制
import re
list_words = ["cat", "dog", "animals","adam"]
text = "I have a lot of animals,       cat and a     dog"

for word in list_words:
    if word in text:
        word = re.search(r" (\s*{})".format(word), text).group(1)
        text = text.replace(f" {word}", f", {word}")
print(text)

但我在这里有两个问题:

1:如果我有这样的文字:text= I have a lot of animals cat and a dogy

它把它变成:text= I have a lot of, animals, cat and a, dogy

这不是我想要的结果,我只想用这个词来代替它本身。

加法类dogy

如果我有这样的文字:text= I have a lot of animals, cat and a dogy

它仍然添加了另一个逗号,这不是我想要的。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-05-27 19:36:45

您可以使用

代码语言:javascript
复制
,*(\s*\b(?:cat|dog|animals|adam))\b

见regex演示。详细信息

  • ,* -零或多个逗号
  • (\s*\b(?:cat|dog|animals|adam)) -第1组:
    • \s* -零或多个空白空间
    • \b -一个单词边界
    • (?:cat|dog|animals|adam) -其中一个词

  • \b -字边界

见Python演示

代码语言:javascript
复制
import re
list_words = ["cat", "dog", "animals", "adam"]
text = "I have a lot of animals,       cat and a     dog"
pattern = r",*(\s*\b(?:{}))\b".format("|".join(list_words))
print( re.sub(pattern, r",\1", text) )
# => I have a lot of, animals,       cat and a,     dog
票数 1
EN

Stack Overflow用户

发布于 2021-05-27 17:53:06

所有的单词都有一个逗号:

代码语言:javascript
复制
import re

list_words = ["cat", "dog", "animals"]
text = "I have a lot of animals a cat and a dog"

for word in list_words:
    word = re.search(r" (\s*{}) ".format(word), text)
    text = text.replace(f" {word}", f", {word}")
票数 1
EN

Stack Overflow用户

发布于 2021-05-27 17:54:22

用一种简单的方法。

代码语言:javascript
复制
list_words =["cat","dog","animals"]
text = "I have a lot of animals a cat and a dog"
test_list_words=[]
for new in text.split(" "):
        if new in list_words:
                new=new+","
                test_list_words.append(new)
        else:
                test_list_words.append(new)
print(' '.join(test_list_words))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67727434

复制
相关文章

相似问题

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