使用已知的幻灯片索引和 shape_id 替换图表中的数据
Replacing data in a chart with known slide index and shape_id
我想更新条形图中的数据,但在访问包含图表的对象的步骤中出现错误。这是给我 shape_id 的代码:
shp=prs.slides[0].shapes
for shape in shp:
print(
"id: %s, type: %s, name: %s"
% (shape.shape_id, shape.shape_type, shape.name)
)
# => **Output:** id: 7, type: CHART (3), name: Chart 6
但是,当我尝试使用 shape_id 定义图表对象时,出现以下错误:
图表 = prs.slides[0].shapes[7].图表
错误:
raise IndexError("shape index out of range")
IndexError: shape index out of range
我也试过这个代码:chart = shp._spTree.shape_id[7].chart
错误:
TypeError: 'int' object is not subscriptable
问题是您将 shape-id 作为 index 用于形状序列。 shape-id 不对应于该形状在形状 "list".
中的位置
要按 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
或者如果你做了很多,你可以使用字典来完成这项工作:
shapes_by_id = dict((s.shape_id, s) for s in shapes)
然后为您提供所有方便的 dict
方法,例如:
>>> 7 in shapes_by_id
True
>>> shapes_by_id[7]
<pptx.shapes.Shape object at 0x...>
我想更新条形图中的数据,但在访问包含图表的对象的步骤中出现错误。这是给我 shape_id 的代码:
shp=prs.slides[0].shapes
for shape in shp:
print(
"id: %s, type: %s, name: %s"
% (shape.shape_id, shape.shape_type, shape.name)
)
# => **Output:** id: 7, type: CHART (3), name: Chart 6
但是,当我尝试使用 shape_id 定义图表对象时,出现以下错误: 图表 = prs.slides[0].shapes[7].图表
错误:
raise IndexError("shape index out of range")
IndexError: shape index out of range
我也试过这个代码:chart = shp._spTree.shape_id[7].chart
错误:
TypeError: 'int' object is not subscriptable
问题是您将 shape-id 作为 index 用于形状序列。 shape-id 不对应于该形状在形状 "list".
中的位置要按 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
或者如果你做了很多,你可以使用字典来完成这项工作:
shapes_by_id = dict((s.shape_id, s) for s in shapes)
然后为您提供所有方便的 dict
方法,例如:
>>> 7 in shapes_by_id
True
>>> shapes_by_id[7]
<pptx.shapes.Shape object at 0x...>