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 的建议,我已成功将文本提取为如下内容:
['\n\t\t','n\t\tMESSAGE SET\n\t\t','\n\t\t','\n\t\t1. 1/1/09 - sample text 1,....,'\n\t']
通过一些清理,我想我可以得到很好的文本,但是,我丢失了关联的节点 ID 值。
代码:
from lxml import etree
from StringIO import StringIO
xmlfile = ('C:\...AnnotationsXML.xml')
xmldoc = etree.parse(xmlfile)
print xmldoc.xpath("//TextWithNodes/text()")
所以我想我的问题是:
- 有没有办法在没有\n\t\t 的情况下提取上述内容?我读到它是空格格式(即制表符),但我不确定
<Node id = 0>
在哪里去。 - 提取此文件是否有更好或更有效的方法?
谢谢!
最佳答案
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'}
关于python - 从此 XML 文件中提取数据的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11127361/