我有一个单词列表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"
到目前为止我的代码是:
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
它仍然添加了另一个逗号,这不是我想要的。
发布于 2021-05-27 19:36:45
您可以使用
,*(\s*\b(?:cat|dog|animals|adam))\b见regex演示。详细信息
,* -零或多个逗号(\s*\b(?:cat|dog|animals|adam)) -第1组:\s* -零或多个空白空间\b -一个单词边界(?:cat|dog|animals|adam) -其中一个词\b -字边界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发布于 2021-05-27 17:53:06
所有的单词都有一个逗号:
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}")发布于 2021-05-27 17:54:22
用一种简单的方法。
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))https://stackoverflow.com/questions/67727434
复制相似问题