擅长:python、mysql、java
<p>您可以将<code>re.sub</code>与通过连接列表中的单词创建的交替模式一起使用。在单词边界断言<code>\b</code>中包含交替模式,以便它只匹配整个单词。使用负的lookback和lookahead来避免匹配已经用双引号括起来的单词:</p>
<pre><code>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))
</code></pre>
<p>这将输出:</p>
<pre><code>Sita has "apple" and "plum" and loves drinking snapple
</code></pre>
<p>演示:<a href="https://ideone.com/Tf9Aka" rel="nofollow noreferrer">https://ideone.com/Tf9Aka</a></p>