2010-06-24 1 views
0

내 텍스트의 형식이다 태그의 마지막 발생을 캡처 :

<Story> 
<Sentence id="1"> some text </Sentence> 
<Sentence id="2"> some text </Sentence> 
<Sentence id="3"> some text </Sentence> 

내 작업은 지난 </Sentence> 후 닫는 태그 </Story>를 삽입하는 것입니다. 본문에서, 모든 </Sentence> 다음에는 3 칸이옵니다. 나는 정규 표현식 </Sentence>(?!.*<Sentence)을 사용하여 마지막으로 캡처를 시도하고 re.DOTALL도 사용했다. 그러나 그것은 작동하지 않습니다. 사용

실제 코드를 도와주세요
line = re.sub(re.compile('</Sentence>(?!.*<Sentence)',re.DOTALL),'</Sentence></Story>',line)

입니다. 감사.

+3

당신은 정말 [파서를 사용]한다 (http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)에 대한 이. –

+0

@David @msw 잘못된 xml을 파서로 사용 하시겠습니까? 파서는 형식이 올바르지 않은 XML 문서를 볼 때 예외를 throw하지 않습니까? – afs

+1

좋은 점, 일부는 있지만 일부는 누락 된 태그를 인식하고 자동으로 추가 할 수 있습니다. 나는 그것이 상황에 달려 있다고 생각한다. 그리고 파서가 예외를 던지더라도 유효하지 않은 태그의 위치를 ​​포함 할 수 있습니다.이 태그는 ''태그를 삽입 할 장소입니다. –

답변

3

전체 코드를 생성하는 코드가 동일합니까? 그렇다면 XML 라이브러리를 사용하여 생성 한 다음 모든 태그가 올바르게 중첩됩니다. 코드를 생성하지 않으면 올바른 XML이됩니다.

정규식과 xml은 잘 어울리지 않습니다.

+0

사용중인 코드가 문장 태그를 생성합니다. 루트 태그를 붙여서 유효한 XML이되도록 노력하고 있습니다. ' afs

+2

@afs : ''+ 문장 + '''을 사용할 수없는 몇 가지 이유가 있습니까? –

1

실제로 작업을 수행하려면 BeautifulSoup과 같은 파서를 사용해야합니다. BeautifulSoup은 매우 잘못된 HTML/XML을 구문 분석하여 올바르게 보이게 만듭니다. BeautifulSoup로 그것을 구문 분석하는 방법을

from BeautifulSoup import BeautifulStoneSoup 

html = ''' 
<Document> 
<PrevTag></PrevTag> 
<Story> 
<Sentence id="1"> some text </Sentence> 
<Sentence id="2"> some text </Sentence> 
<Sentence id="3"> some text </Sentence> 
<EndTag></EndTag> 
</Document> 
''' 
# Parse the document: 
soup = BeautifulStoneSoup(html) 

봐 :

코드는 (당신이 전에 당신의 잘못된 Story 태그 다음에 어떤 태그가 있으리라 믿고있어, 그렇지 않으면 당신은 다윗의 코멘트에서 조언을 따를 것입니다)과 같이 수
print soup.prettify() 

#<document> 
# <prevtag> 
# </prevtag> 
# <story> 
# <sentence id="1"> 
# some text 
# </sentence> 
# <sentence id="2"> 
# some text 
# </sentence> 
# <sentence id="3"> 
# some text 
# </sentence> 
# <endtag> 
# </endtag> 
# </story> 
#</document> 

BeautifulSoup이 (문서)를 감싸는 태그를 닫기 전에 이야기를 닫았 기 때문에 마지막 문장 옆에있는 닫기 태그를 이동해야합니다.

# Find the last sentence: 
last_sentence = soup.findAll('sentence')[-1] 

# Find the Story tag: 
story = soup.find('story') 

# Move all tags after the last sentence outside the Story tag: 
sib = last_sentence.nextSibling 
while sib: 
    story.parent.append(sib.extract()) 
    sib = last_sentence.nextSibling 

print soup.prettify() 

#<document> 
# <prevtag> 
# </prevtag> 
# <story> 
# <sentence id="1"> 
# some text 
# </sentence> 
# <sentence id="2"> 
# some text 
# </sentence> 
# <sentence id="3"> 
# some text 
# </sentence> 
# </story> 
# <endtag> 
# </endtag> 
#</document> 

최종 결과는 정확히 원하는 결과 여야합니다. 이 코드는 문서에 스토리가 하나만 있다고 가정합니다. 그렇지 않은 경우 약간 수정해야합니다. 행운을 빕니다! 당신이 필요로하는 모든 태그의 마지막 발생을 찾을 경우

0

, 당신은 할 수 있습니다

reSentenceClose= re.compile('</Sentence> *') 
match= None 
for match in reSentenceClose.finditer(your_text): 
    pass 

if match: # it was found 
    print match.end() # the index in your_text where the pattern was found 
0

이유는 세 가지 (또는 그러나 많은) <Sentence> 요소를 일치하지 및 그룹 참조에 다시 연결?

re.sub(r'(?:(\r?\n) *<Sentence.*?</Sentence> *)+', 
     r'$0$1</Story>', 
     line)