jjzjj

python - 没有在 python 中正确解析嵌套的 xml 标签

coder 2024-07-01 原文

我在 python 中处理 XML 文件。我有一个包含多种语言的句子的数据集,其结构如下:

<corpus>
  <sentence id="0">
    <text lang="de">...</text>
    <text lang="en">...</text>
    <text lang="fr">...</text>
    <!-- Other languages -->
    <annotations>
      <annotation lang="de">...</annotation>
      <annotation lang="en">...</annotation>
      <annotation lang="fr">...</annotation>
      <!-- Other languages -->
    </annotations>
  </sentence>
  <sentence id="1">
    <!-- Other sentence -->
  </sentence>
  <!-- Other sentences -->
</corpus>

我想得到的是,从数据集开始,一个新的数据集只包含句子和英文注释(属性“lang”的“en”值)。我试过这个解决方案:

import xml.etree.ElementTree as ET
tree = ET.parse('samplefile2.xml')
root = tree.getroot()
for sentence in root:
  if sentence.tag == 'sentence':
    for txt in sentence:
      if txt.tag == 'text':
        if txt.attrib['lang'] != 'en':
          sentence.remove(txt)
      if txt.tag == 'annotations':
        for annotation in txt:
          if annotation.attrib['lang'] != 'en':
            txt.remove(annotation)
tree.write('output.xml')

但是好像只在text属性层面起作用,在annotation属性层面不起作用。我什至尝试用增量索引 root[s]、root[s][t]、root[s][t ][a],但是排序没有效果。此外,我提供的 python 代码在 xml 文件中随机插入(老实说,我不知道这是否有助于解决这个问题)像 δημι 这样的字符串;ουργία

所以,我坚信问题出在嵌套标签中,但我无法弄清楚。一些想法?

最佳答案

如果您能够使用 lxml,我认为使用 xpath 会更容易...

XML 输入 (input.xml)

<corpus>
  <sentence id="0">
    <text lang="de">...</text>
    <text lang="en">...</text>
    <text lang="fr">...</text>
    <!-- Other languages -->
    <annotations>
      <annotation lang="de">...</annotation>
      <annotation lang="en">...</annotation>
      <annotation lang="fr">...</annotation>
      <!-- Other languages -->
    </annotations>
  </sentence>
  <sentence id="1">
    <!-- Other sentence -->
  </sentence>
  <!-- Other sentences -->
</corpus>

python

from lxml import etree

target_lang = "en"

tree = etree.parse("input.xml")

# Match any element that has a child that has a lang attribute with a value other than
# target_lang. We need this element so we can remove the child from it.
for parent in tree.xpath(f".//*[*[@lang != '{target_lang}']]"):
    # Match the children that have a lang attribute with a value other than target_lang.
    for child in parent.xpath(f"*[@lang != '{target_lang}']"):
        # Remove the child from the parent.
        parent.remove(child)

tree.write("output.xml")

XML 输出 (output.xml)

<corpus>
  <sentence id="0">
    <text lang="en">...</text>
    <!-- Other languages -->
    <annotations>
      <annotation lang="en">...</annotation>
      <!-- Other languages -->
    </annotations>
  </sentence>
  <sentence id="1">
    <!-- Other sentence -->
  </sentence>
  <!-- Other sentences -->
</corpus>

关于python - 没有在 python 中正确解析嵌套的 xml 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56085245/

有关python - 没有在 python 中正确解析嵌套的 xml 标签的更多相关文章

  1. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  2. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  3. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  4. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  5. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  6. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  7. ruby - 用逗号、双引号和编码解析 csv - 2

    我正在使用ruby​​1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\

  8. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  9. ruby-on-rails - rails 目前在重启后没有安装 - 2

    我有一个奇怪的问题:我在rvm上安装了ruby​​onrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(

  10. ruby - 在院子里用@param 标签警告 - 2

    我试图使用yard记录一些Ruby代码,尽管我所做的正是所描述的here或here#@param[Integer]thenumberoftrials(>=0)#@param[Float]successprobabilityineachtrialdefinitialize(n,p)#initialize...end虽然我仍然得到这个奇怪的错误@paramtaghasunknownparametername:the@paramtaghasunknownparametername:success然后生成的html看起来很奇怪。我称yard为:$yarddoc-mmarkdown我做错了什么?

随机推荐