使用 Python 中的 ElementTree,如何从节点中提取所有文本,剥离该元素中的任何标签并仅保留文本?
例如,假设我有以下内容:
<tag>
Some <a>example</a> text
</tag>
我想回来Some example text
。我该怎么做呢?到目前为止,我所采取的方法已经产生了相当灾难性的结果。
如果您在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,可以复用实施itertext() https://github.com/python/cpython/blob/2.7/Lib/xml/etree/ElementTree.py#L498通过将其附加到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'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)