如何将python-docx/pptx的文档核心属性转为可用Python对象?
Python-PPTX:将CorePropertiesPart转为易用属性对象
首先明确:prs.core_properties本身就是可用对象,你看到的<pptx.parts.coreprops.CorePropertiesPart at ...>只是这个对象的字符串表示,不影响你直接访问它的属性(比如prsProps.modified、prsProps.author这些你已经在代码里验证过是有效的)。
如果你希望得到一个更“干净”、只包含文档属性的对象,可以用以下两种方式实现:
方法1:转为字典或SimpleNamespace
把核心属性提取到字典,或者用types.SimpleNamespace转为可通过属性访问的轻量对象:
from pptx import Presentation import os from types import SimpleNamespace pptFile = "myfile.pptx" prs = Presentation(os.path.realpath(pptFile)) core_props = prs.core_properties # 定义需要提取的属性列表(从__dir__里筛选出的文档属性) prop_names = [ "author", "category", "comments", "content_status", "created", "identifier", "keywords", "language", "last_modified_by", "last_printed", "modified", "revision", "subject", "title", "version" ] # 方式A:转为字典 props_dict = {name: getattr(core_props, name) for name in prop_names} # 方式B:转为SimpleNamespace(支持属性访问) prsProps = SimpleNamespace(**props_dict) # 使用示例 print(prsProps.modified) print(prsProps.author)
方法2:自定义封装类
如果需要更灵活的操作(比如修改属性后同步回原文档),可以自定义一个类来封装CorePropertiesPart:
from pptx import Presentation import os class DocProperties: def __init__(self, core_props): self._core_props = core_props # 定义需要代理的属性 self._prop_names = [ "author", "category", "comments", "content_status", "created", "identifier", "keywords", "language", "last_modified_by", "last_printed", "modified", "revision", "subject", "title", "version" ] def __getattr__(self, name): if name in self._prop_names: return getattr(self._core_props, name) raise AttributeError(f"'DocProperties' object has no attribute '{name}'") def __setattr__(self, name, value): if name == "_core_props" or name == "_prop_names": super().__setattr__(name, value) elif name in self._prop_names: setattr(self._core_props, name, value) else: raise AttributeError(f"'DocProperties' object has no attribute '{name}'") # 使用示例 pptFile = "myfile.pptx" prs = Presentation(os.path.realpath(pptFile)) prsProps = DocProperties(prs.core_properties) # 读取属性 print(prsProps.modified) # 修改属性(会同步回原文档,保存后生效) prsProps.author = "New Author" prs.save("modified.pptx")
补充说明
- 原
CorePropertiesPart对象本身完全支持读写属性,如果你只是需要访问属性,直接使用prs.core_properties即可,不需要额外转换。 - 上述两种方法的核心是筛选出
__dir__里的文档属性,避免包含类内部的私有属性和方法。
内容的提问来源于stack exchange,提问作者Fred
相关产品推荐
相关产品推荐

