你可以通过re模块来做到这一点。这里模式的顺序非常重要。由于'organizations of human rights'
位于'human rights'
之前,因此正则表达式引擎会尝试首先找到organizations of human rights
这个字符串。如果发现匹配,则它将用[
+匹配+ ]
取代匹配。然后它转到下一个模式,即human rights
是否通过前一模式找到匹配。现在这个human rights
模式将匹配organizations of human rights
字符串中不存在的所有human rights
字符串。因为默认情况下regex不会进行重叠匹配。如果你想要正则表达式模式做一个重叠匹配,那么你需要把模式放在周围,模式必须被()
(,即捕获组)包围。
>>> ex = ['liberty of freedom', 'liberty', 'organizations of human rights', 'human rights']
>>> file = " The american people enjoys a liberty of freedom and there are many international organizations of human rights."
>>> reg = '|'.join(ex)
>>> import re
>>> re.sub('('+reg+')', r'[\1]', file)
' The american people enjoys a [liberty of freedom] and there are many international [organizations of human rights].'