2013-06-20 23 views
0

我希望在Python中使用正则表达式来读取文本,找到其中情感>标记存在于<位置>标记相同句子中的所有实例,然后允许这些句子打印到输出文件的独特行:Python正则表达式扼流器 n

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吗?我会非常感谢别人可以借用这个问题的任何建议。

+0

在应用正则表达式之前,将文件读取为行或删除换行符。 – Andenthal

回答

1

加入再re.S or re.DOTALL(它们是一回事)的标志在你的正则表达式。这将导致.也匹配换行符。所以flags参数的新值将是re.I | re.S

+0

谢谢F.J!我很欣赏这个解释! – duhaime

0

使用re.DOTALL/re.S

flags = re.DOTALL | re.I 
+0

非常感谢,爆炸药丸! – duhaime