【问题标题】:Why am I not getting the text in the XML tag? - python elementtree为什么我没有得到 XML 标记中的文本? - 蟒蛇元素树
【发布时间】: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


    【解决方案1】:

    首先,您的代码有错误。 for corpus in root 不是必须的,你的 root 已经是 corpus

    你可能打算做的是:

    for lexelt in root:
      for instance in lexelt:
        for context in instance:
          contexts.append(context.text)
    

    现在,关于您的问题 - 在 for context in instance 块内,您可以访问您需要的其他两个字符串:

    1. head 文本可以通过访问context.find('head').text 来访问
    2. head 元素右侧的文本可以通过访问context.find('head').tail 来读取 根据Python etree docs

    tail 属性可用于保存与 元素。该属性通常是一个字符串,但也可以是任何 特定于应用程序的对象。如果元素是从 XML 创建的 文件属性将包含元素结束后找到的任何文本 标签和下一个标签之前。

    【讨论】:

    • 你的意思是我的根已经是corpus 或者我的根在开始时已经是context
    【解决方案2】:

    在 ElementTree 中,您必须考虑子节点的 tail 属性。在您的情况下,语料库也是根。

    导入 xml.etree.ElementTree 作为 et 输入文件 = "./coach.data" corpus = et.parse(open(inputfile)).getroot() def getalltext(elem): return elem.text + ''.join([getalltext(child) + child.tail for child in elem]) 实例 = [] 对于语料库中的 lexelt: 例如在 lexelt 中: instance.append(getalltext(instance)) j=1 对于 i 在实例中: 打印“实例”+ j 打印“左:” + i 打印“\n” j+=1

    【讨论】:

    • 谢谢,getalltext(elem) 在python的元素树中确实很有用,应该建议在下一个元素树版本中包含这个配方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多