首页 > 解决方案 > 如何使用 python-pptx 从 powerpoint 中的组形状中的文本形状中提取文本。

问题描述

我的 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 到达这些子元素但我得到一个错误,这些是“属性”类型的,所以我无法访问文本或迭代(TypeError:“属性”对象不可迭代)他们。

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)

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

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

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

标签: pythontextpowerpointpython-pptx

解决方案


我认为你需要这样的东西:

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属性以避免引发异常,例如图片形状。


推荐阅读