用XML解析句子中的多个实例 - Python

时间:2013-04-12 04:22:50

标签: python xml xml-parsing elementtree

我有一个xml文件,它具有以下结构,我在instances中有几个sentence

<corpus>
  <text>
    <sentence>
      <instance\>
      <instance\>
      <instance\>
    <\sentence>
  <\text>
<\corpus>

如何使用句子中的所有实例提取整个句子?

当我尝试sentence.text时,它只给出了第一个实例之前的单词, sentence.find('instance').text只给我第一个实例的字符串 sentence.find('instance').tail仅在下一个实例之前的第一个实例之后给出了单词。

我试过这个,因为我更喜欢elementtree的简单性:

import xml.etree.ElementTree as et
input = '''<corpus lang="en">
<text id="d001">
<sentence id="d001.s001">
Your
Oct
.
6
<instance id="d001.s001.t001" lemma="editorial" pos="n">editorial</instance>
``
The
<instance id="d001.s001.t002" lemma="Ill" pos="a">Ill</instance>
<instance id="d001.s001.t003" lemma="Homeless" pos="n">Homeless</instance>
''
<instance id="d001.s001.t004" lemma="refer" pos="v">referred</instance>
to
<instance id="d001.s001.t005" lemma="research" pos="n">research</instance>
by
us
and
<instance id="d001.s001.t006" lemma="six" pos="a">six</instance>
of
our
<instance id="d001.s001.t007" lemma="colleague" pos="n">colleagues</instance>
that
was
<instance id="d001.s001.t008" lemma="report" pos="v">reported</instance>
in
the
Sept
.
8
<instance id="d001.s001.t009" lemma="issue" pos="n">issue</instance>
of
the
Journal
of
the
American
Medical
Association
.
</sentence>
</text>
</corpus>'''
print>>open('tempfile','a+), input
corpus = et.parse('tempfile').getroot()
for text in corpus:
  for sentence in text:
    before1st = sentence.text
    instance1st = sentence.find('instance').text
    after1st = sentence.find('instance').tail
    print str(before1st + instance1st + after1st).replace("\n"," ").strip()

以上代码仅输出:

Your Oct . 6 editorial `` The 

所需的输出应该是完整的句子:

Your Oct . 6 editorial `` The Ill Homeless '' to research by us and six of our colleagues that was reported in the Sept . 8 issue of the Journal of the American Medical Association

1 个答案:

答案 0 :(得分:1)

要获得所有匹配,请使用findall

out = []
sentences = corpus.findall('.//sentence')
for sentence in sentences:
    out.append(sentence.text)
    instances = sentence.findall('instance')
    for instance in instances:
        out.append(instance.text)
        out.append(instance.tail)
    out.append(sentence.tail)

filterout = []
for i in out:
    txt = i.replace('\n', ' ').strip()
    if len(txt):
        filterout.append(txt)
print ' '.join(filterout)