![](/img/trans.png)
[英]Python - using docx to extract texts with certain features from word documents
[英]Python: Extract XML texts except under certain tags
我有这个示例 XML 文件:
<page>
<title>Chapter 1</title>
<content>Welcome to Chapter 1</content>
<author>John Smith</author>
</page>
<page>
<title>Chapter 2</title>
<content>Welcome to Chapter 2</content>
<author>John Doe</author>
</page>
这个 XML 可能有多个级别(即超过 2 个)并且可能有其他标签。 我希望提取除“内容”标签下的文本之外的所有文本,以便获得如下字符串列表:
['Chapter 1', 'John Smith', 'Chapter 2', 'John Doe']
我正在使用 ElementTree 执行此任务。 有没有优雅、干净的解决方案?
import bs4
xml = '''<page>
<title>Chapter 1</title>
<content>Welcome to Chapter 1</content>
<author>John Smith</author>
</page>
<page>
<title>Chapter 2</title>
<content>Welcome to Chapter 2</content>
<author>John Doe</author>
</page>'''
soup = bs4.BeautifulSoup(xml, 'lxml')
[(page.title.text, page.author.text)for page in soup('page')]
出去:
[('Chapter 1', 'John Smith'), ('Chapter 2', 'John Doe')]
使用 BeautifulSoup 作为 XML 解析器,可以参考Document
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.