python - 使用 Python 解析 XML:将文本保留在属性内,同时删除其周围的标签
问题描述
Input:
<p>
<milestone n="14" unit="verse" />
The name of the third river is
<placeName key="tgn,1130850" authname="tgn,1130850">Hiddekel</placeName>: this is the one which flows in front of Assyria. The fourth
river is the <placeName key="tgn,1123842" authname="tgn,1123842">Euphrates</placeName>.
</p>
期望的输出:
<p>
<milestone n="14" unit="verse" />
The name of the third river is Hiddekel: this is the one which flows in front of Assyria. The fourth river is the Euphrates.
</p>
您好,我想找到一种方法来从子元素 ( placeName
) 中提取文本并将其放回较大的文本正文中。我在 XML 文件的其他地方也有类似的问题,例如人名。我希望能够在不摆脱里程碑的情况下提取名称和地点。谢谢您的帮助!
当前代码:
for p in chapter.findall('p'):
i = 1
for text in p.itertext():
file.write(body.attrib["n"] + " " + chapter.attrib["n"] + ":" + str(i) + text)
i = i + 1
解决方案
可以用beautifulsoup和unwrap()
方法来完成:
from bs4 import BeautifulSoup as bs
snippet = """your html above"""
soup = bs(snippet,'lxml')
pl = soup.find_all('placename')
for p in pl:
p.unwrap()
soup
输出:
<html><body><p>
<milestone n="14" unit="verse"></milestone>
The name of the third river is
Hiddekel: this is the one which flows in front of Assyria. The fourth
river is the Euphrates.
</p>
</body></html>
推荐阅读
- java - 尝试在 sublime 中构建 Latex 文档会导致 Java 错误
- python - 我该如何解决这个问题:错误:命令出错,退出状态为 1:尝试“pip install psycopg2”时
- c - 头文件中辅助函数中的动态内存分配问题
- django - 如何从 ModelForm 访问外键/ OneToOneField 表的数据?
- database - 带有 SQFlite 的“警告数据库已被锁定”警告和代码停止。为什么我不能查询表?
- api - 如何将 API 响应正文或属性保存在环境变量或 json 中,以便以后在赛普拉斯的其他请求中使用它
- python - 摆脱文件中的特定单词
- azure-virtual-network - 如何使 VPN 连接从 Azure VM 工作?
- c# - 我可以在 Azure DevOps 中使用 dotnet publish 命令发布 .net framework 4.7.1 解决方案吗
- jq - 如何“编号”数组项?