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
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)
您可以将
re.sub
与通过连接列表中的单词创建的交替模式一起使用。在单词边界断言\b
中包含交替模式,以便它只匹配整个单词。使用负的lookback和lookahead来避免匹配已经用双引号括起来的单词:这将输出:
演示:https://ideone.com/Tf9Aka
不使用regex的解决方案:
re.sub
可以很好地处理这个问题相关问题 更多 >
编程相关推荐