我有一个单词列表,例如:
["apple", "orange", "plum"]
我只想对字符串中的这些单词添加引号:
Rita has apple ----> Rita has "apple"
Sita has "apple" and plum ----> Sita has "apple" and "plum"
如何使用正则表达式在python中实现此目标?
答案 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
答案 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)