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

2024-04-28 11:50:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

如何使用正则表达式在python中实现这一点?你知道吗


Tags: and字符串apple列表单词引号hasorange
3条回答

您可以将re.sub与通过连接列表中的单词创建的交替模式一起使用。在单词边界断言\b中包含交替模式,以便它只匹配整个单词。使用负的lookback和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

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

不使用regex的解决方案:

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可以很好地处理这个问题

import re

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

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

print(mystr)

相关问题 更多 >