python - 现有演示文稿中每张 pptx 幻灯片的形状编号/索引
问题描述
我是 python pptx 库的新手,我的问题是:如何使用 Python Library pptx 在现有演示文稿中定义每个 pptx 幻灯片的形状列表、形状编号/索引(shapetree)和形状类型?我想更新现有的 ppt 演示文稿,似乎第一步是在每张幻灯片上找到确切的形状标识符,以便通过更新访问它们。您能给我指出一个现有的解决方案或可能的例子吗?
解决方案
我假设“定义”是指“发现”之类的东西,因为通常没有充分的理由来更改现有值。
一个好的开始方法是循环并打印一些属性:
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...>
推荐阅读
- java - 尽管关闭了小数宽度,但 macOS Retina 上的 OpenJDK 11 Swing 等宽字体渲染问题
- django - 第一次django_project/密码重置超时错误
- sql-server - SQL Server:按 8 个生成小时对数据进行分组
- python - os.path.splitext() 无法有效工作导致不正确的扩展输出
- java - 如何获取包含网格视图的整个列表项的单击事件?
- python - 当我在 selenium 中使用 execute_script 命令时,我不断收到 SyntaxError
- python - 从不同目录和文件中的 python 模块访问全局变量时出现问题
- c++ - 使用 std::vector::swap 方法在 C++ 中交换两个不同的向量是否安全?
- google-bigquery - unnest 是否始终在 Bigquery 中按命中数的升序显示数据
- sql - SQL - 检查日期是否在数据库中