2013-06-20 33 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