核心代码解析
1. 颜色转换函数:rgb_to_hex
将rgb颜色值(如(255, 0, 0)
)转换为十六进制字符串(如#ff0000
)。
当前代码存在缺陷:原函数直接返回rgb元组,而非十六进制字符串。以下是修正后的实现:
def rgb_to_hex(rgb): """将 rgb 颜色转换为十六进制字符串(如 #ff0000)""" if rgb is none: return none return f"#{rgb[0]:02x}{rgb[1]:02x}{rgb[2]:02x}"
2. 解析单个形状:parse_shape
提取形状的类型、位置、样式、文本内容等信息,支持文本框、表格、图片等类型。
关键步骤:
- 基础属性:形状类型(如
mso_shape_type.text_box
)、位置(left
,top
)、尺寸(width
,height
)。 - 填充样式:颜色类型(纯色/渐变)、颜色值(十六进制)。
- 边框样式:颜色、线宽、虚线类型(如
mso_line_dash_style.dash
)。 - 文本样式:段落对齐、字体名称、大小、加粗/斜体、颜色。
- 特殊处理:
- 表格:解析行、列及单元格内容。
- 图片:记录尺寸信息。
示例输出(文本框):
{ "type": 1, // mso_shape_type.text_box "name": "text box 1", "text": "hello world", "fill": { "type": "mso_fill.solid", "color": "#ff0000" }, "line": { "color": "#000000", "width": 12700, // emu单位 "dash_style": "mso_line_dash_style.solid" }, "text_style": { "paragraphs": [ { "text": "hello world", "runs": [ { "text": "hello world", "font": { "name": "arial", "size": 24, "bold": false, "color": "#000000" } } ] } ] } }
3. 解析整个ppt:parse_presentation
遍历ppt的每一页和每个形状,调用parse_shape
生成结构化数据。
示例输出(json片段):
{ "slides": [ { "slide_number": 254, // ppt内部id "shapes": [ { "type_name": "mso_shape_type.table", "table": [ [ {"text": "header 1", "row_span": 1, "col_span": 1}, {"text": "header 2", "row_span": 1, "col_span": 1} ], [ {"text": "row 1", "row_span": 1, "col_span": 1}, {"text": "data", "row_span": 1, "col_span": 1} ] ] } ] } ] }
4. 保存为json:save_to_json
将解析结果以可读格式保存为文件。
def save_to_json(data, output_path): with open(output_path, "w", encoding="utf-8") as f: json.dump(data, f, indent=4, ensure_ascii=false)
使用示例
1. 安装依赖
pip install python-pptx
2. 运行代码
if __name__ == "__main__": input_pptx = "template.pptx" # 输入ppt路径 output_json = "presentation_info.json" # 输出json路径 parsed_data = parse_presentation(input_pptx) save_to_json(parsed_data, output_json)
3. 输出json结构
{ "slides": [ { "slide_number": 254, "shapes": [ { "type": 1, "name": "text box 1", "text": "sample text", "fill": {"type": "mso_fill.background", "color": null}, "line": {"color": null, "width": 0, "dash_style": null}, "text_style": { "paragraphs": [ { "text": "sample text", "runs": [ { "text": "sample text", "font": { "name": "calibri", "size": 11, "bold": false, "color": "#000000" } } ] } ] } } ] } ] }
核心功能与适用场景
1. 支持的形状类型
类型名称 | 对应值 | 描述 |
---|---|---|
mso_shape_type.text_box | 1 | 文本框 |
mso_shape_type.table | 19 | 表格 |
mso_shape_type.picture | 17 | 图片 |
其他形状 | 根据mso枚举 | 形状、线条等 |
2. 典型应用场景
- 样式复用:提取模板样式,批量生成符合规范的ppt。
- 数据迁移:将ppt内容导出为json,用于数据分析或内容管理。
- 自动化生成:结合json数据,动态生成ppt(需反向实现
apply
功能)。
注意事项
单位转换:
- ppt中的尺寸单位为emu(english metric unit),可通过
shape.width/9525
转换为像素(1 emu ≈ 0.01像素)。
- ppt中的尺寸单位为emu(english metric unit),可通过
异常处理:
- 部分形状可能无文本框(如图片),需通过
shape.has_text_frame
判断。 - 颜色值可能为
none
(如填充为透明色),需设置默认值。
- 部分形状可能无文本框(如图片),需通过
扩展建议:
- 支持更多样式:如阴影、3d效果。
- 反向生成ppt:根据json数据重建ppt文件。
总结
通过本文的代码和解析,开发者可以快速实现ppt文件的自动化解析与数据提取。无论是学术研究、企业报告自动化,还是结合llm生成内容,这一工具链都能提供强大的基础支持。下一步,你可以尝试:
- 结合llm生成内容:用gpt生成文本后,填充到json的
text
字段。 - 可视化样式:将json数据渲染为网页或图表,用于ppt设计预览。
通过python和json的结合,ppt的自动化处理从未如此简单!
import json from pptx import presentation from pptx.enum.shapes import mso_shape_type from pptx.enum.text import pp_align from pptx.enum.dml import mso_fill, mso_line_dash_style def rgb_to_hex(rgb): """将 rgb 颜色转换为十六进制字符串(如 #ff0000)""" if rgb is none: return none return (rgb[0], rgb[1], rgb[2]) def parse_shape(shape): """解析单个 shape 的信息""" data = { "type": shape.shape_type, "type_name": str(mso_shape_type(shape.shape_type)), "name": shape.name, "left": shape.left, "top": shape.top, "width": shape.width, "height": shape.height, "rotation": shape.rotation, "text": "", "fill": {}, "line": {}, "text_style": {} } # 解析填充样式 fill = shape.fill try: data["fill"] = { "type": str(mso_fill(fill.type)), "color": rgb_to_hex(fill.fore_color.rgb) if fill.fore_color else none } except: data["fill"] = { "type": str(mso_fill(fill.type)), "color": none } # 解析边框样式 line = shape.line # try: data["line"] = { "color": rgb_to_hex(line.color.rgb) if line.color.type else none, "width": line.width, "dash_style": str(mso_line_dash_style(line.dash_style)) if line.dash_style else none } # except: # print() # 解析文本样式(如果存在文本框) if shape.has_text_frame: text_frame = shape.text_frame paragraphs = [] for paragraph in text_frame.paragraphs: runs = [] for run in paragraph.runs: run_data = { "text": run.text, "font": { "name": run.font.name, "size": run.font.size.pt, "bold": run.font.bold, "italic": run.font.italic, "color": rgb_to_hex(run.font.color.rgb) } } runs.append(run_data) paragraph_data = { "text": paragraph.text, "runs": runs, "level": paragraph.level, "alignment": str(pp_align(paragraph.alignment)) if paragraph.alignment else none } paragraphs.append(paragraph_data) data["text_style"] = { "paragraphs": paragraphs } data["text"] = text_frame.text # 处理表格 if shape.shape_type == mso_shape_type.table: table = shape.table rows = [] for row in table.rows: cells = [] for cell in row.cells: cell_data = { "text": cell.text.strip(), "row_span": cell.row_span, "col_span": cell.col_span } cells.append(cell_data) rows.append(cells) data["table"] = rows # 处理图片 if shape.shape_type == mso_shape_type.picture: data["image"] = { "width": shape.width, "height": shape.height } return data def parse_presentation(pptx_path): """解析整个 ppt 文件并返回 json 结构""" prs = presentation(pptx_path) presentation_data = { "slides": [] } for slide_idx, slide in enumerate(prs.slides): slide_data = { "slide_number": slide.slide_id, "shapes": [] } for shape in slide.shapes: shape_data = parse_shape(shape) slide_data["shapes"].append(shape_data) presentation_data["slides"].append(slide_data) return presentation_data def save_to_json(data, output_path): """将解析后的数据保存为 json 文件""" with open(output_path, "w", encoding="utf-8") as f: json.dump(data, f, indent=4, ensure_ascii=false) # 使用示例 if __name__ == "__main__": input_pptx = "template.pptx" # 输入的 ppt 文件路径 output_json = "presentation_info.json" # 输出的 json 文件路径 # 解析 ppt parsed_data = parse_presentation(input_pptx) # 保存为 json save_to_json(parsed_data, output_json)
以上就是使用python解析ppt文件并生成json结构详解的详细内容,更多关于python解析ppt并生成json的资料请关注代码网其它相关文章!
发表评论