我有一个单词列表,例如:
["apple", "orange", "plum"]
我只想为字符串中的这些单词添加引号:
Rita has apple ----> Rita has "apple"
Sita has "apple" and plum ----> Sita has "apple" and "plum"
如何使用正则表达式在 python 中实现此目的?
最佳答案
您可以将 re.sub
与通过连接列表中的单词创建的交替模式一起使用。将交替模式括在字边界断言 \b
中,以便它仅匹配整个单词。使用负lookbehind和lookahead来避免匹配已经用双引号括起来的单词:
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
关于python - 使用正则表达式向 python 句子中的单词列表添加引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55287514/