首页 > 解决方案 > 是否有读取 ms office 文件的底层 xml 的 python 包?

问题描述

我想在 python 中读取 PPTX 文件的 XML,基本上将字符串/数据结构保存到变量中。

我还没有找到可以让我用 Python 做到这一点的包。

标签: pythonxmlxml-parsingoffice365powerpoint

解决方案


如果我理解正确,您可以使用内置zipfile模块。

import zipfile
archive = zipfile.ZipFile('<My Powerpoint Name>.pptx', 'r')
xml_file = archive.open('[Content_Types].xml')
text = xml_file.read()
print(text)

这将[Content_Types].xml直接从存档中打印出 xml 文本。

如果要解析 XML,可以使用内置xml模块。

import zipfile
import xml.etree.ElementTree as ET

archive = zipfile.ZipFile('<My Powerpoint Name>.pptx', 'r')
xml_file = archive.open('[Content_Types].xml')
text = xml_file.read()

root = ET.fromstring(text)
value_to_find = r'application/vnd.openxmlformats-package.relationships+xml'
for child in root:
    if child.attrib['ContentType'] == value_to_find:
        print(child.attrib)

推荐阅读