0

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 にヒットしたときにチョークしないように、この正規表現を変更する方法はありますか? 他の人がこの質問に貸すことができるアドバイスをいただければ幸いです。

4

2 に答える 2

1

正規表現のフラグにrere.Sまたはre.DOTALL(それらは同じものです) を追加します。これにより.、改行にも一致します。flagsしたがって、引数の新しい値は になりますre.I | re.S

于 2013-06-20T16:15:42.247 に答える