替换文件中的字符串 - python

我有一个表达式列表,我想替换文件中的每个表达式。

我尝试了这段代码

for a in ex:
   if a in file.split():
       file = file.replace(a, '[' + ' ' + a + ' ' +']')
print file

我的代码也替换了括号之间另一个表达式的一部分的表达式。所以我想要的是只替换不属于方括号之间的另一个表达式的表达式。
如何获得理想的结果?

python大神给出的解决方案

您可以通过re模块来做到这一点。在此模式的顺序非常重要。由于'organizations of human rights'位于'human rights'之前,因此正则表达式引擎将首先尝试查找此字符串organizations of human rights。如果找到匹配项,则将其替换为[ + match + ]。然后,它前进至下一个模式,即human rights是否通过上一个模式找到匹配项。现在,此human rights模式将匹配human rights字符串中不存在的所有organizations of human rights字符串。因为默认情况下,正则表达式不会进行重叠匹配。如果要让正则表达式模式进行重叠匹配,则需要将模式放在环视范围内,并且模式必须用()包围(即捕获组)。

>>> 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].'