gpt4 book ai didi

Python元素树——从元素中提取文本,剥离标签

转载 作者:太空狗 更新时间:2023-10-29 20:35:23 24 4
gpt4 key购买 nike

使用 Python 中的 ElementTree,我如何从节点中提取所有文本,去除该元素中的所有标签并仅保留文本?

例如,假设我有以下内容:

<tag>
Some <a>example</a> text
</tag>

我想返回一些示例文本。我该怎么做呢?到目前为止,我采用的方法产生了相当灾难性的后果。

最佳答案

如果您在 Python 3.2+ 下运行,您可以使用 itertext

itertext 创建一个文本迭代器,它按文档顺序循环遍历此元素和所有子元素,并返回所有内部文本:

import xml.etree.ElementTree as ET
xml = '<tag>Some <a>example</a> text</tag>'
tree = ET.fromstring(xml)
print(''.join(tree.itertext()))

# -> 'Some example text'

如果你运行的是低版本的Python,可以重用the implementation of itertext()通过将它附加到 Element 类,之后你可以像上面一样调用它:

# original implementation of .itertext() for Python 2.7
def itertext(self):
tag = self.tag
if not isinstance(tag, basestring) and tag is not None:
return
if self.text:
yield self.text
for e in self:
for s in e.itertext():
yield s
if e.tail:
yield e.tail

# if necessary, monkey-patch the Element class
if 'itertext' not in ET.Element.__dict__:
ET.Element.itertext = itertext

xml = '<tag>Some <a>example</a> text</tag>'
tree = ET.fromstring(xml)
print(''.join(tree.itertext()))

# -> 'Some example text'

关于Python元素树——从元素中提取文本,剥离标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19369901/

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