繁体   English   中英

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

[英]Add quotes to a list of words in a sentence in python using regular expressions

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

["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

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

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM