首页 > 解决方案 > 现有演示文稿中每张 pptx 幻灯片的形状编号/索引

问题描述

我是 python pptx 库的新手,我的问题是:如何使用 Python Library pptx 在现有演示文稿中定义每个 pptx 幻灯片的形状列表、形状编号/索引(shapetree)和形状类型?我想更新现有的 ppt 演示文稿,似乎第一步是在每张幻灯片上找到确切的形状标识符,以便通过更新访问它们。您能给我指出一个现有的解决方案或可能的例子吗?

标签: pythonpython-pptx

解决方案


我假设“定义”是指“发现”之类的东西,因为通常没有充分的理由来更改现有值。

一个好的开始方法是循环并打印一些属性:

prs = Presentation("my-deck.pptx")
for slide in prs.slides:
    for shape in slide.shapes:
        print("id: %s, type: %s" % (shape.shape_id, shape.shape_type))

使用此处的 API 文档中列出的任何幻灯片和/或形状属性,您可以根据需要获得尽可能详细的信息:
https ://python-pptx.readthedocs.io/en/latest/api/shapes.html#一般形状对象

要通过 id(或名称)查找形状,您需要如下代码:

def find_shape_by_id(shapes, shape_id):
    """Return shape by shape_id."""
    for shape in shapes:
        if shape.shape_id == shape_id:
            return shape
    return None

或者如果你做了很多工作,你可以使用 adict来完成这项工作:

shapes_by_id = dict((s.shape_id, s) for s in shapes)

然后为您提供所有方便的方法,例如:

>>> 7 in shapes_by_id
True
>>> shapes_by_id[7]
<pptx.shapes.Shape object at 0x...>

推荐阅读