![](/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.