この作業を行うには、BeautifulSoupのようなパーサーを使用する必要があります。BeautifulSoup は、非常に不正確な HTML/XML を解析して、正しく見えるようにしようとします。コードは次のようになります (間違ったタグの前後にいくつかのタグがあると仮定しています。Story
そうでない場合は、David のコメントのアドバイスに従うことになります)。
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)
BeautifulSoup がどのように解析したかを見てください。
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 は Story を囲むタグ (Document) を閉じる直前に閉じていることに注意してください。そのため、最後の文の隣に閉じタグを移動する必要があります。
# 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>
最終結果は、まさにあなたが望んでいたものになるはずです。このコードは、ドキュメント内にストーリーが 1 つしかないことを前提としていることに注意してください。そうでない場合は、少し変更する必要があります。幸運を!