使用python-pptx提取PPT文本时部分内容丢失的问题求助
解决python-pptx提取PPT文本丢失的问题
导致文本未被提取的常见原因是目标文本位于分组形状(Group Shape)或表格单元格中,原代码仅遍历了幻灯片的顶层形状,未处理嵌套结构的内容,而这些内容在XML中是存在的。以下是针对性的解决方案:
1. 处理分组形状的递归提取
修改代码,增加对分组形状的递归遍历,深入提取内部子形状的文本:
from pptx import Presentation def extract_text_from_shape(shape, text_runs): # 递归处理分组形状(MsoShapeType.GROUP对应数值6) if shape.shape_type == 6: for sub_shape in shape.shapes: extract_text_from_shape(sub_shape, text_runs) return # 提取普通文本框内容 if not shape.has_text_frame: return for paragraph in shape.text_frame.paragraphs: for run in paragraph.runs: if run.text.strip(): # 可选:过滤空白文本 text_runs.append(run.text) def getPptContent(path): prs = Presentation(path) text_runs = [] for slide in prs.slides: for shape in slide.shapes: extract_text_from_shape(shape, text_runs) return text_runs
2. 额外处理表格内的文本
如果丢失的文本位于表格中,在上述基础上添加表格处理逻辑:
from pptx import Presentation def extract_text_from_shape(shape, text_runs): # 递归处理分组形状 if shape.shape_type == 6: for sub_shape in shape.shapes: extract_text_from_shape(sub_shape, text_runs) return # 提取表格单元格内的文本 if shape.has_table: for row in shape.table.rows: for cell in row.cells: for paragraph in cell.text_frame.paragraphs: for run in paragraph.runs: if run.text.strip(): text_runs.append(run.text) return # 提取普通文本框内容 if not shape.has_text_frame: return for paragraph in shape.text_frame.paragraphs: for run in paragraph.runs: if run.text.strip(): text_runs.append(run.text) def getPptContent(path): prs = Presentation(path) text_runs = [] for slide in prs.slides: for shape in slide.shapes: extract_text_from_shape(shape, text_runs) return text_runs
上述代码覆盖了绝大多数文本丢失的场景,通过递归遍历嵌套形状和表格结构,能完整提取XML中存在的所有文本内容。
内容的提问来源于stack exchange,提问作者data_person
相关产品推荐
相关产品推荐

