使用正则表达式将引号添加到python语句中的单词列表中
我有一个单词列表,如:使用正则表达式将引号添加到python语句中的单词列表中,python,regex,python-3.6,Python,Regex,Python 3.6,我有一个单词列表,如: ["apple", "orange", "plum"] 我只想在字符串中为这些单词添加引号: Rita has apple ----> Rita has "apple" Sita has "apple" and plum ----> Sita has "apple" and "plum" 如何在python中使用正则表达式实现这一点?不使用正则表达式的解决方案: re.sub可以很好地为您处理此问题 重新导入 mystr=“丽塔有苹果” mylist=[
["apple", "orange", "plum"]
我只想在字符串中为这些单词添加引号:
Rita has apple ----> Rita has "apple"
Sita has "apple" and plum ----> Sita has "apple" and "plum"
如何在python中使用正则表达式实现这一点?不使用正则表达式的解决方案:
re.sub
可以很好地为您处理此问题
重新导入
mystr=“丽塔有苹果”
mylist=[“苹果”、“橘子”、“李子”]
对于mylist中的项目:
mystr=re.sub(项目'\'%s\''%item,mystr)
打印(mystr)
您可以将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))
演示:这是一个很酷的单行程序,但什么是交替模式?交替模式是一种使用交替操作符将多个模式合并在一起的模式。看,我得读点书,这是一个有趣的功能,我还没有看到before@C.Nivs:此解决方案中的另一个有趣特性称为零长度断言,在本例中可见为
\b
:正如re模块的文档所述:它匹配\w
和\w
@user2728024之间的边界,这正是单词边界断言的含义\b
是用于。它确保匹配只出现在单词的边界处,因此apple
不会匹配snapple
。如果句子是“丽塔喝苹果味的snapple?”
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