我希望在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嗎?我會非常感謝別人可以借用這個問題的任何建議。
在應用正則表達式之前,將文件讀取爲行或刪除換行符。 – Andenthal