2

I'm trying to extract text from powerpoint text boxes with the following code:

from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE

def iter_textable_shapes(shapes):
    for shape in shapes:
        if shape.has_text_frame:
            yield shape

def iter_textframed_shapes(shapes):
    """Generate shape objects in *shapes* that can contain text.

    Shape objects are generated in document order (z-order), bottom to top.
    """
    for shape in shapes:
        # ---recurse on group shapes---
        if shape.shape_type == MSO_SHAPE_TYPE.GROUP:
            group_shape = shape
            for shape in iter_textable_shapes(group_shape.shapes):
                yield shape
            continue

        # ---otherwise, treat shape as a "leaf" shape---
        if shape.has_text_frame:
            yield shape

prs = Presentation(path_to_my_prs)
 
for slide in prs.slides:
    textable_shapes = list(iter_textframed_shapes(slide.shapes))
    ordered_textable_shapes = sorted(
        textable_shapes, key=lambda shape: (shape.top, shape.left)
    )

    for shape in ordered_textable_shapes:
        print(shape.text)

But sometimes the textbox at the end of the ppt is extracted first and sometimes the ones in the middle and so on. How do I fix my code to get the text in correct order (left-to-right, top-to-bottom) ?

wbzy00
  • 146
  • 9

0 Answers0