gpt4 book ai didi

python - 删除一个元素,但不删除其后的文本

转载 作者:太空宇宙 更新时间:2023-11-04 06:04:31 25 4
gpt4 key购买 nike

我有一个 XML类似这样的文件:

<root>
<a>Some <b>bad</b> text <i>that</i> I <u>do <i>not</i></u> want to keep.</a>
</root>

我想删除 <b> 中的所有文本或 <u>元素(和后代),并打印其余部分。这是我尝试过的:

from __future__ import print_function
import xml.etree.ElementTree as ET

tree = ET.parse('a.xml')
root = tree.getroot()

parent_map = {c:p for p in root.iter() for c in p}

for item in root.findall('.//b'):
parent_map[item].remove(item)
for item in root.findall('.//u'):
parent_map[item].remove(item)
print(''.join(root.itertext()).strip())

(我使用 this answer 中的配方构建了 parent_map )。当然,问题在于 remove(item)我还删除了元素后面的文本,结果是:

Some that I

而我想要的是:

Some  text that I  want to keep.

有什么解决办法吗?

最佳答案

如果你最终不会使用更好的东西,你可以使用 clear() 而不是 remove() 保留元素的尾部:

import xml.etree.ElementTree as ET


data = """<root>
<a>Some <b>bad</b> text <i>that</i> I <u>do <i>not</i></u> want to keep.</a>
</root>"""

tree = ET.fromstring(data)
a = tree.find('a')
for element in a:
if element.tag in ('b', 'u'):
tail = element.tail
element.clear()
element.tail = tail

print ET.tostring(tree)

打印(见空的 bu 标签):

<root>
<a>Some <b /> text <i>that</i> I <u /> want to keep.</a>
</root>

此外,这是一个使用 xml.dom.minodom 的解决方案:

import xml.dom.minidom

data = """<root>
<a>Some <b>bad</b> text <i>that</i> I <u>do <i>not</i></u> want to keep.</a>
</root>"""

dom = xml.dom.minidom.parseString(data)
a = dom.getElementsByTagName('a')[0]
for child in a.childNodes:
if getattr(child, 'tagName', '') in ('u', 'b'):
a.removeChild(child)

print dom.toxml()

打印:

<?xml version="1.0" ?><root>
<a>Some text <i>that</i> I want to keep.</a>
</root>

关于python - 删除一个元素,但不删除其后的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22967659/

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