gpt4 book ai didi

python - 当文本之间的元素时提取 xml 文本

转载 作者:行者123 更新时间:2023-12-01 01:14:44 25 4
gpt4 key购买 nike

我有这个 xml 文件:

<do title='Example document' date='today'>
<db descr='First level'>
<P>
Some text here that
<af d='reference 1'>continues</af>
but then has some more stuff.
</P>
</db>

我需要解析它以提取其文本。我正在使用xml.etree.ElementTree为此(see documentation)。

这是我用来解析和探索文件的简单代码:

import xml.etree.ElementTree as ET
tree = ET.parse(file_path)
root = tree.getroot()

def explore_element(element):
print(element.tag)
print(element.attrib)
print(element.text)
for child in element:
explore_element(child)

explore_element(root)

一切按预期工作,除了元素 <P>没有完整的文本。特别是,我似乎缺少“但还有更多内容”(<P> 中的文本位于 <af> 元素之后)。

xml 文件是给定的,所以我无法改进它,即使有更好的推荐方法来编写它(并且有太多需要尝试手动修复)。

有什么办法可以获取所有文本吗?

我的代码产生的输出(如果有帮助的话)是这样的:

do
{'title': 'Example document', 'date': 'today'}

db
{'descr': 'First level'}

P
{}
Some text here that

af
{'d': 'reference 1'}
continues

编辑:

被接受的答案让我意识到我没有像我应该的那样仔细阅读文档。有相关问题的人也可能会发现 .tail 很有用。

最佳答案

使用BeautifulSoup:

list_test.xml:

<do title='Example document' date='today'>
<db descr='First level'>
<P>
Some text here that
<af d='reference 1'>continues</af>
but then has some more stuff.
</P>
</db>

然后:

from bs4 import BeautifulSoup

with open('list_test.xml','r') as f:
soup = BeautifulSoup(f.read(), "html.parser")
for line in soup.find_all('p'):
print(line.text)

输出:

Some text here that
continues
but then has some more stuff.

编辑:

使用elementree:

import xml.etree.ElementTree as ET
xml = '<p> Some text here that <af d="reference 1">continues</af> but then has some more stuff.</p>'
tree = ET.fromstring(xml)
print(''.join(tree.itertext()))

输出:

Some text here that continues but then has some more stuff.

关于python - 当文本之间的元素时提取 xml 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54459807/

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