gpt4 book ai didi

python - 如何迭代 ElementTree 中的子文本节点(不是后代)?

转载 作者:行者123 更新时间:2023-12-01 04:58:18 24 4
gpt4 key购买 nike

给定一个这样的元素

<A>
hello

<annotation> NOT part of text </annotation>

world
</A>

如何使用 ElementTree 获取子文本节点(如 XPath text())?

iter()itertext() 都是树遍历器,其中包括所有后代节点。据我所知,没有直接子迭代器。另外,无论如何,iter() 只能查找元素(毕竟是ElementTree),因此不能用于收集文本节点。

我知道有一个名为 lxml 的库,它提供了更好的 XPath 支持,但我在添加另一个依赖项之前在这里询问。 (另外,我对 Python 还很陌生,所以我可能会遗漏一些明显的东西。)

最佳答案

您发现示例文本的三个属性有些违反直觉:

  • “你好”的文本
  • annotation.text 表示“不是文本的一部分”
  • “世界”的annotation.tail

(省略空格)。这有点麻烦。然而,沿着这些思路的一些东西应该会有所帮助:

 import xml.etree.ElementTree as et

xml = """
<A>
hello

<annotation> NOT part of text </annotation>

world
</A>"""


doc = et.fromstring(xml)


def all_texts(root):
if root.text is not None:
yield root.text
for child in root:
if child.tail is not None:
yield child.tail


print list(all_texts(doc))

关于python - 如何迭代 ElementTree 中的子文本节点(不是后代)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26869875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com