gpt4 book ai didi

python - 如何使用 python-pptx 从 powerpoint 中的组形状中的文本形状中提取文本。

转载 作者:行者123 更新时间:2023-11-28 22:17:03 26 4
gpt4 key购买 nike

我的 PowerPoint 幻灯片有许多组形状,其​​中有子文本形状。

之前我使用过这段代码,但它不处理组形状。

for eachfile in files:
prs = Presentation(eachfile)

textrun=[]
for slide in prs.slides:
for shape in slide.shapes:
if hasattr(shape, "text"):
print(shape.text)
textrun.append(shape.text)
new_list=" ".join(textrun)
text_list.append(new_list)

我正在尝试从这些子文本框中提取文本。我已经设法使用 GroupShape.shape 到达这些子元素但是我得到一个错误,这些是“property”类型,所以我无法访问文本或迭代(TypeError:“property”对象不可迭代)。

from pptx.shapes.group import GroupShape
from pptx import Presentation
for eachfile in files:
prs = Presentation(eachfile)

textrun=[]
for slide in prs.slides:
for shape in slide.shapes:
for text in GroupShape.shapes:
print(text)

然后我想捕获文本并附加到一个字符串以供进一步处理。

所以我的问题是,如何访问子文本元素并从中提取文本。

我花了很多时间浏览文档和源代码,但一直没弄明白。任何帮助将不胜感激。

最佳答案

我想你需要这样的东西:

from pptx.enum.shapes import MSO_SHAPE_TYPE

for slide in prs.slides:
# ---only operate on group shapes---
group_shapes = [
shp for shp in slide.shapes
if shp.shape_type == MSO_SHAPE_TYPE.GROUP
]
for group_shape in group_shapes:
for shape in group_shape.shapes:
if shape.has_text_frame:
print(shape.text)

组形状包含其他形状,可在其 .shapes 属性中访问。它本身具有.text 属性。因此,您需要迭代组中的形状并从每个形状中获取文本。

请注意,此解决方案仅深入一层。可以使用递归方法按深度优先遍历树,并从包含组的组中获取文本(如果有的话)。

另请注意,并非所有形状都有文本,因此您必须检查 .has_text_frame 属性以避免在图片形状上引发异常。

关于python - 如何使用 python-pptx 从 powerpoint 中的组形状中的文本形状中提取文本。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51701626/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com