从pptx中提取文本并在excel中导出

问题描述

我使用以下代码从 pptx 中提取文本

from pptx import Presentation

import glob

for eachfile in glob.glob(r"C:\Users\Desktop\powerpoint file\*.pptx"):
    prs = Presentation(eachfile)
    
    for slide in prs.slides:
        for shape in slide.shapes:
            if hasattr(shape,"text"):
                print(shape.text)

输入 pptx 看起来像这样。

enter image description here

enter image description here

输出如下(不按顺序)我也想在excel中导出它 - 请帮忙

enter image description here

预期输出

enter image description here

解决方法

出现在幻灯片上的形状形成一个 sequence,按 z-order 排序,就像列表后面的形状在列表前面的形状“顶部”一样。

它们不会以某种“从左到右、从上到下阅读的顺序”出现。

如果您希望文本按照读者最自然地扫描的顺序出现,您需要考虑每个形状的位置,并可能按 (top,left) 对它们进行排序。虽然这可能只是一个开始,但您可能需要更复杂的规则来解释扫描方式不同的文本“列”等内容。

这个问题源于这样一个事实,即与 Microsoft Word 文档不同,PowerPoint 幻灯片的内容不是流动,也没有自然的“内容”或“阅读”顺序,只有“什么形状堆叠在其他形状上面的视觉”序列。