2015-02-23 137 views
2

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

我尝试这个代码

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

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

回答

5

你可以通过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].'