【发布时间】:2012-09-14 12:35:24
【问题描述】:
如何阅读<context>...</context> 标签中的所有文本?那么<context \>标签中的<head>...<\head>标签呢?
我有一个如下所示的 XML 文件:
<corpus lang="english">
<lexelt item="coach.n">
<instance id="1">
<context>I'll buy a train or <head>coach</head> ticket.</context>
</instance>
<instance id="2">
<context>A branch line train took us to Aubagne where a <head>coach</head> picked us up for the journey up to the camp.</context>
</instance>
</lexelt>
</corpus>
但是当我运行我的代码来读取 ... 中的 XML 文本时,我只能在到达标签之前获取文本。
import xml.etree.ElementTree as et
inputfile = "./coach.data"
root = et.parse(open(inputfile)).getroot()
instances = []
for corpus in root:
for lexelt in corpus:
for instance in lexelt:
instances.append(instance.text)
j=1
for i in instances:
print "instance " + j
print "left: " + i
print "\n"
j+=1
现在我只是在左侧:
instance 1
left: I'll buy a train or
instance 2
left: A branch line train took us to Aubagne where a
输出还需要上下文和头部的右侧,应该是:
instance 1
left: I'll buy a train or
head: coach
right: ticket.
instance 2
left: A branch line train took us to Aubagne where a
head: coach
right: picked us up for the journey up to the camp.
【问题讨论】:
标签: python xml elementtree readxml