2013-10-20 3 views
-2

파일에 저장된 2 개의 태그 사이에서 내용을 읽으려고합니다. 내용이 여러 줄에 걸쳐있을 수 있습니다. 태그는 파일에서 0 번 또는 1 번 발생할 수 있습니다.파이썬에서 2 개의 태그 사이에 문자열 찾기

예를 들어 "콘텐츠"읽는 동안 파일의 내용이, 그래서

title:Corruption Today: Corruption today in 
content:Corruption Today: 
Corruption today in 
score:0.91750675 

할 수있다, 내 쿼리는 "부패 오늘 : 부패를 오늘"결과를해야한다. 는 일부 인터넷 검색 후, 나는 우리가 콘텐츠를 검색 할 포함한 FileContent을 통해 2 번 반복 될 때 얼마나 코드 위의 효율적인 확실하지 않다 코드

myfile = open(files,'r'); 
filecontent = myfile.read(); 

startPtrs = [m.start()+8 for m in re.finditer('content:', filecontent)]; 
startPtr = startPtrs[0]; 
endPtrs = [m.start()-1 for m in re.finditer('score:', filecontent)]; 
endPtr = endPtrs[0]; 

content = filecontent[startPtr:endPtr]; 

다음 쓸 수 있어요. 더 효율적인 것을 할 수 있습니까?

+0

볼 수 있습니다

here은 또한 다른 솔루션이 있습니다 볼 수 있습니까? 예를 들어'content'가 여러 번 나타날 수 있습니까? –

+0

'태그'란 무엇입니까? 콜론':'이 포함 된 모든 행에 태그가 있습니까? –

+0

@KobiK : 위에 지정된대로 태그는 0 번 또는 1 번 발생할 수 있습니다. 따라서 "내용 :"이 존재하거나 존재하지 않습니다. –

답변

0

당신이 re moudle를 사용하여이 문자열 beetwen 문자열을 찾으려면 :

import re 

myfile = open(files,'r'); 
filecontent = myfile.read(); 

results = re.compile('content(.*?)score', re.DOTALL | re.IGNORECASE).findall(filecontent) 
print results 

일부 설명 : 문서에서

IGNORECASE :

대소 문자를 구분 일치를 수행; [A-Z]와 같은 표현식은 소문자와도 일치합니다. 현재 로케일의 영향을받지 않습니다. 문서에서

DOTALL :

(Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline. 

Compile 당신이 전체 파일 here

관련 문제