Files
MechanicalNotes/重写规范/tools/extract_pptx.py
T

45 lines
1.4 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
"""Extract all text (text frames + tables, incl. group shapes) from a .pptx into a UTF-8 txt.
Usage: python extract_pptx.py <input.pptx> <output.txt>
"""
import sys
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE
def iter_shapes(shapes):
for sh in shapes:
yield sh
if sh.shape_type == MSO_SHAPE_TYPE.GROUP:
try:
yield from iter_shapes(sh.shapes)
except Exception:
pass
def main(src, out):
prs = Presentation(src)
lines = []
for idx, slide in enumerate(prs.slides, 1):
lines.append("")
lines.append("===== SLIDE %d =====" % idx)
for sh in iter_shapes(slide.shapes):
if sh.has_text_frame:
txt = "\n".join(p.text for p in sh.text_frame.paragraphs if p.text and p.text.strip())
if txt.strip():
lines.append(txt)
try:
if sh.has_table and sh.has_table:
for row in sh.table.rows:
cells = [c.text.replace("\n", " ") for c in row.cells]
lines.append(" | ".join(cells))
except Exception:
pass
with open(out, "w", encoding="utf-8") as f:
f.write("\n".join(lines))
print("OK: %d lines -> %s" % (len(lines), out))
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2])