0

我的文本格式如下:

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

我的任务是</Story>在最后一个</Sentence>. 在正文中,every</Sentence>后跟 3 个空格。我尝试使用正则表达式捕获最后一个</Sentence></Sentence>(?!.*<Sentence)并且也使用了 re.DOTALL。但它不起作用。

实际使用的代码是
line = re.sub(re.compile('</Sentence>(?!.*<Sentence)',re.DOTALL),'</Sentence></Story>',line)

请帮忙。谢谢。

4

4 回答 4

3

生成整个文件的代码是否相同 - 如果是,则使用 xml 库生成它,然后所有标签都将正确嵌套 - 如果不修复生成它的代码,使其成为有效的 XML。

正则表达式和 xml 不能很好地结合在一起。

于 2010-06-24T06:17:01.887 回答
1

你真的应该使用像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 在关闭它的标签(文档)之前关闭了故事,因此您必须将结束标签移动到最后一句话旁边。

# 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>

最终结果应该正是您想要的。请注意,此代码假定文档中只有一个 Story——如果没有,则应稍作修改。祝你好运!

于 2010-06-24T07:20:00.617 回答
0

为什么不匹配所有三个(或多个)<Sentence>元素并使用组引用将它们重新插入?

re.sub(r'(?:(\r?\n) *<Sentence.*?</Sentence> *)+',
       r'$0$1</Story>',
       line)
于 2010-06-25T13:34:33.283 回答
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
于 2010-06-25T12:02:53.283 回答