2013-06-20 4 views
0

텍스트를 읽는 Python에서 정규 표현식을 사용하고 < 감정> 마크 업이 < 위치> 마크 업과 동일한 문장으로 존재하는 모든 인스턴스를 찾은 다음 해당 문장을 출력 파일의 독특한 라인 : I 줄 바꿈이 포함 된 파일을 읽을 경우, 정규 표현식은 실패Python regex chokes on 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