Python正则表达式扼杀\ n

时间:2013-06-20 16:08:44

标签: python regex search line-breaks proximity

我希望在Python中使用正则表达式来读取文本,找到所有<情感>标记存在于与<位置>标记,然后允许这些句子打印到输出文件的唯一行:

import re
out = open('out.txt', 'w')

readfile = "<location> Oklahoma </location> where the wind comes <emotion> sweeping </emotion> down <location> the plain </location>. And the waving wheat. It can sure smell <emotion> sweet </emotion>." 

for match in re.findall(r'(?:(?<=\.)\s+|^)((?=(?:(?!\.(?:\s|$)).)*?\bemotion>(?=\s|\.|$))(?=(?:(?!\.(?:\s|$)).)*?\blocation>(?=\s|\.|$)).*?\.(?=\s|$))', readfile, flags=re.I):
    line = ''.join(str(x) for x in match)
    out.write(line + '\n')

out.close()

问题是,如果我读入包含换行符的文件,则正则表达式失败:

import re
out = open('out.txt', 'w')

readfile = "<location> Oklahoma </location> where the wind \n comes <emotion> sweeping </emotion> down <location> the plain </location>. And the waving wheat. It can sure smell <emotion> sweet </emotion>." 

for match in re.findall(r'(?:(?<=\.)\s+|^)((?=(?:(?!\.(?:\s|$)).)*?\bemotion>(?=\s|\.|$))(?=(?:(?!\.(?:\s|$)).)*?\blocation>(?=\s|\.|$)).*?\.(?=\s|$))', readfile, flags=re.I):
    line = ''.join(str(x) for x in match)
    out.write(line + '\n')

out.close()

有没有办法修改这个正则表达式,以便在它到达时不会阻塞\ n?我非常感谢其他人可以就这个问题提出任何建议。

2 个答案:

答案 0 :(得分:1)

将re re.S or re.DOTALL(它们是同一个东西)添加到正则表达式中的标记。这将导致.也匹配换行符。因此flags参数的新值为re.I | re.S

答案 1 :(得分:0)

使用re.DOTALL / re.S

flags = re.DOTALL | re.I