从这个XML fi中提取数据的最有效方法

2024-10-05 15:29:56 发布

您现在位置:Python中文网/ 问答频道 /正文

XML文件示例

<GateDocument> 
  <GateDocumentFeatures>
    ...
  </GateDocumentFeatures>
  <TextWithNodes>
    <Node id="0"/>
    MESSAGE SET
    <Node id="19"/> 
    <Node id="20"/>
    1. 1/1/09 - sample text 1
    <Node id="212"/>
    sample text 2
    <Node id="223"/>
    sample text 3
    ...
    <Node id="160652"/>
  </TextWithNodes>
  <AnnotationSet></AnnotationSet>
  <AnnotationSet Name="SomeName">
    ...
  </AnnotationSet>
</GateDocument>

首先,这是我第一次用Python编写代码并处理XML,如果我错过了非常明显的东西,很抱歉!在

我的目标是提取特定节点id处的示例文本。在

第一次尝试-我使用了minidom,它没有给我正确的方法来处理提取(http://stackoverflow.com/questions/11122736/extracting-text-from-xml-node-with-minidom)因为在自动关闭标记中节点id的这种奇怪的格式。在

第二次尝试-我在查看lxml时接受了一些建议,我成功地将文本提取为如下内容:

^{pr2}$

通过一些清理,我想我可以很好地获得文本,但是,我丢失了关联的节点id值。在

使用代码:

from lxml import etree
from StringIO import StringIO
xmlfile = ('C:\...AnnotationsXML.xml')
xmldoc = etree.parse(xmlfile)  
print xmldoc.xpath("//TextWithNodes/text()")

所以我想我的问题是:

  1. 是否有一种方法可以在不使用\n\t\t的情况下提取上述内容?我读到这是空间格式化(即tab),但我不确定<Node id = 0>去了哪里。在
  2. 有没有更好或更有效的方法来提取这个文件?在

谢谢!在


Tags: 文件sample方法textfrom文本idnode
1条回答
网友
1楼 · 发布于 2024-10-05 15:29:56
In [1]: from lxml import etree

In [2]: tree = etree.parse('awful.xml')

In [3]: data = {int(node.attrib['id']): node.tail.strip()
   ...: for node in tree.xpath('//TextWithNodes/Node') if node.tail.strip()}

In [4]: data
Out[4]: 
{0: 'MESSAGE SET',
 20: '1. 1/1/09 - sample text 1',
 212: 'sample text 2',
 223: 'sample text 3'}

^{}用于删除\t\n之类的内容,^{}接受标记后的文本。在

相关问题 更多 >