gpt4 book ai didi

python /元素树 : Parsing inline elements w/respect to surrounding text?

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:53 25 4
gpt4 key购买 nike

我需要解析一些包含内联 元素的 XML。例如,XML 看起来像这样:

<section>
Fubar, I'm so fubar, fubar and even more <fref bar="baz">fubare</fref>. And yet more fubar.
</section>

如果我现在用 for elem in list(parent): ... 遍历这个结构我只能访问 fref。如果我现在处理 fref,周围的文本当然会丢失,因为文本不是真正的元素。

有人知道如何正确解决这个问题吗?

最佳答案

下面显示了如何使用 lxml 实现这一点。

>>> from lxml.etree import fromstring
>>> tree = fromstring('''<section> Fubar, I'm so fubar, fubar and even more <fref bar="baz">fubare</fref>. And yet more fubar. </section>''')
>>> elem = tree.xpath('/section/fref')[0]
>>> elem.text
'fubare'
>>> elem.tail
'. And yet more fubar. '
>>> elem.getparent().text
" Fubar, I'm so fubar, fubar and even more "

来自 lxml.etree tutorial :

If you want to read only the text, i.e. without any intermediate tags, you have to recursively concatenate all text and tail attributes in the correct order. Again, the tostring() function comes to the rescue, this time using the method keyword:

>>> from lxml.etree import tostring
>>> tostring(html, method="text")
" Fubar, I'm so fubar, fubar and even more fubare. And yet more fubar. "

还有一种 XPath 方法可以做到这一点,链接页面中对此进行了描述。

关于 python /元素树 : Parsing inline elements w/respect to surrounding text?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10180781/

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