【问题标题】:Parsing multiple instance within a sentence in XML - Python在 XML 中解析一个句子中的多个实例 - Python
【发布时间】:2013-04-12 04:22:50
【问题描述】:

我有一个具有以下结构的 xml 文件,其中我在 sentence 中有多个 instances

<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

【问题讨论】:

    标签: python xml xml-parsing elementtree


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2016-11-12
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多