使用正则表达式将引号添加到python句子中的单词列表中

时间:2019-03-21 18:58:52

标签: python regex python-3.6

我有一个单词列表,例如:

["apple", "orange", "plum"]

我只想对字符串中的这些单词添加引号:

Rita has apple  ----> Rita has "apple"
Sita has "apple" and plum ----> Sita has "apple" and "plum"

如何使用正则表达式在python中实现此目标?

3 个答案:

答案 0 :(得分:1)

您可以将re.sub与通过连接列表中的单词而创建的交替模式一起使用。将替换模式包含在单词边界声明\b中,以使其仅匹配整个单词。使用负向后查找和向前查找来避免匹配已经用双引号引起来的单词:

import re
words = ["apple", "orange", "plum"]
s = 'Sita has apple and "plum" and loves drinking snapple'
print(re.sub(r'\b(?!<")(%s)(?!")\b' % '|'.join(words), r'"\1"', s))

这将输出:

Sita has "apple" and "plum" and loves drinking snapple

演示:https://ideone.com/Tf9Aka

答案 1 :(得分:0)

不使用正则表达式的解决方案:

txt = "Sita has apple and plum"
words = ["apple", "orange", "plum"]
txt = " ".join(["\""+w+"\"" if w in words else w for w in txt.split()])
print (txt)

txt = "Rita drinks apple flavored snapple?"
txt = " ".join(["\""+w+"\"" if w in words else w for w in txt.split()])
print (txt)

答案 2 :(得分:0)

re.sub可以很好地为您处理

import re

mystr = "Rita has apple"
mylist = ["apple", "orange", "plum"]

for item in mylist:
    mystr = re.sub(item, '\"%s\"'%item, mystr)

print(mystr)