텍스트를 읽는 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? 다른 사람들이이 질문에 빌려 줄 수있는 조언에 대해 가장 감사하게 생각합니다.
파일을 줄로 읽거나 정규식을 적용하기 전에 줄 바꿈 문자를 제거하십시오. – Andenthal