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

标签 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 与通过连接列表中的单词创建的交替模式一起使用。将交替模式括在字边界断言 \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

关于python - 使用正则表达式向 python 句子中的单词列表添加引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55287514/

相关文章:

java - 如何从另一个字符串中获取与正则表达式匹配的子字符串?

interop - 如何在 Twisted 的 asyncioreactor 之上运行 asyncio 库代码?

python - PDF转换后文件打开异常

python - conda 环境是否可以访问 'root' 环境? (==系统包)?

ios - 在 Swift 中使用正则表达式查找字符串的子字符串

python - 如何创建 .desktop 文件以在 Linux 上启动 python 脚本?

java - 如何处理正则表达式中的字符 "#"?

linux - 运行具有终端其他文件依赖性的 python 脚本时出现问题?

python - 为什么 numba 字典查找比 cpython 慢这么多?

python - 从字符串列表中获取子字符串与某个正则表达式匹配的子字符串列表