gpt4 book ai didi

python - 使用 python 从 XML 中提取文本

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

我有这个示例 xml 文件

<page>
<title>Chapter 1</title>
<content>Welcome to Chapter 1</content>
</page>
<page>
<title>Chapter 2</title>
<content>Welcome to Chapter 2</content>
</page>

我喜欢提取title标签和content标签的内容。

提取数据哪种方法好,使用模式匹配还是使用xml模块。或者有没有更好的方法来提取数据。

最佳答案

已经有一个内置的 XML 库,特别是 ElementTree .例如:

>>> from xml.etree import cElementTree as ET
>>> xmlstr = """
... <root>
... <page>
... <title>Chapter 1</title>
... <content>Welcome to Chapter 1</content>
... </page>
... <page>
... <title>Chapter 2</title>
... <content>Welcome to Chapter 2</content>
... </page>
... </root>
... """
>>> root = ET.fromstring(xmlstr)
>>> for page in list(root):
... title = page.find('title').text
... content = page.find('content').text
... print('title: %s; content: %s' % (title, content))
...
title: Chapter 1; content: Welcome to Chapter 1
title: Chapter 2; content: Welcome to Chapter 2

关于python - 使用 python 从 XML 中提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7691514/

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