使用python从XML中提取文本 [英] Extracting text from XML using python

查看:54
本文介绍了使用python从XML中提取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个示例xml文件

<title>第一章</title><content>欢迎来到第一章</content></页面><页面><title>第二章</title><content>欢迎来到第 2 章</content></页面>

我喜欢提取标题标签和内容标签的内容.

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

解决方案

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

<预><代码>>>>从 xml.etree 导入 cElementTree 作为 ET>>>xmlstr = """... <root>...<页面>... <title>Chapter 1</title>... <content>欢迎来到第 1 章</content>... </page>...<页面>... <title>Chapter 2</title>... <content>欢迎来到第 2 章</content>... </page>... </root>……">>>root = ET.fromstring(xmlstr)>>>对于列表中的页面(根):... title = page.find('title').text... content = page.find('content').text... print('title: %s; content: %s' % (title, content))...标题:第一章;内容:欢迎来到第一章书名:第2章;内容:欢迎来到第 2 章

I have this example xml file

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

I like to extract the contents of title tags and content tags.

Which method is good to extract the data, using pattern matching or using xml module. Or is there any better way to extract the data.

解决方案

There is already a built-in XML library, notably ElementTree. For example:

>>> 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从XML中提取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆