使用Python解析PPT文件并生成JSON結(jié)構(gòu)詳解
核心代碼解析
1. 顏色轉(zhuǎn)換函數(shù):rgb_to_hex
將RGB顏色值(如(255, 0, 0)
)轉(zhuǎn)換為十六進(jìn)制字符串(如#FF0000
)。
當(dāng)前代碼存在缺陷:原函數(shù)直接返回RGB元組,而非十六進(jìn)制字符串。以下是修正后的實(shí)現(xiàn):
def rgb_to_hex(rgb): """將 RGB 顏色轉(zhuǎn)換為十六進(jìn)制字符串(如 #FF0000)""" if rgb is None: return None return f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}"
2. 解析單個(gè)形狀:parse_shape
提取形狀的類型、位置、樣式、文本內(nèi)容等信息,支持文本框、表格、圖片等類型。
關(guān)鍵步驟:
- 基礎(chǔ)屬性:形狀類型(如
MSO_SHAPE_TYPE.TEXT_BOX
)、位置(left
,top
)、尺寸(width
,height
)。 - 填充樣式:顏色類型(純色/漸變)、顏色值(十六進(jìn)制)。
- 邊框樣式:顏色、線寬、虛線類型(如
MSO_LINE_DASH_STYLE.DASH
)。 - 文本樣式:段落對(duì)齊、字體名稱、大小、加粗/斜體、顏色。
- 特殊處理:
- 表格:解析行、列及單元格內(nèi)容。
- 圖片:記錄尺寸信息。
示例輸出(文本框):
{ "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. 解析整個(gè)PPT:parse_presentation
遍歷PPT的每一頁(yè)和每個(gè)形狀,調(diào)用parse_shape
生成結(jié)構(gòu)化數(shù)據(jù)。
示例輸出(JSON片段):
{ "slides": [ { "slide_number": 254, // PPT內(nèi)部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
將解析結(jié)果以可讀格式保存為文件。
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. 運(yùn)行代碼
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結(jié)構(gòu)
{ "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" } } ] } ] } } ] } ] }
核心功能與適用場(chǎng)景
1. 支持的形狀類型
類型名稱 | 對(duì)應(yīng)值 | 描述 |
---|---|---|
MSO_SHAPE_TYPE.TEXT_BOX | 1 | 文本框 |
MSO_SHAPE_TYPE.TABLE | 19 | 表格 |
MSO_SHAPE_TYPE.PICTURE | 17 | 圖片 |
其他形狀 | 根據(jù)MSO枚舉 | 形狀、線條等 |
2. 典型應(yīng)用場(chǎng)景
- 樣式復(fù)用:提取模板樣式,批量生成符合規(guī)范的PPT。
- 數(shù)據(jù)遷移:將PPT內(nèi)容導(dǎo)出為JSON,用于數(shù)據(jù)分析或內(nèi)容管理。
- 自動(dòng)化生成:結(jié)合JSON數(shù)據(jù),動(dòng)態(tài)生成PPT(需反向?qū)崿F(xiàn)
apply
功能)。
注意事項(xiàng)
單位轉(zhuǎn)換:
- PPT中的尺寸單位為EMU(English Metric Unit),可通過(guò)
shape.width/9525
轉(zhuǎn)換為像素(1 EMU ≈ 0.01像素)。
- PPT中的尺寸單位為EMU(English Metric Unit),可通過(guò)
異常處理:
- 部分形狀可能無(wú)文本框(如圖片),需通過(guò)
shape.has_text_frame
判斷。 - 顏色值可能為
None
(如填充為透明色),需設(shè)置默認(rèn)值。
- 部分形狀可能無(wú)文本框(如圖片),需通過(guò)
擴(kuò)展建議:
- 支持更多樣式:如陰影、3D效果。
- 反向生成PPT:根據(jù)JSON數(shù)據(jù)重建PPT文件。
總結(jié)
通過(guò)本文的代碼和解析,開(kāi)發(fā)者可以快速實(shí)現(xiàn)PPT文件的自動(dòng)化解析與數(shù)據(jù)提取。無(wú)論是學(xué)術(shù)研究、企業(yè)報(bào)告自動(dòng)化,還是結(jié)合LLM生成內(nèi)容,這一工具鏈都能提供強(qiáng)大的基礎(chǔ)支持。下一步,你可以嘗試:
- 結(jié)合LLM生成內(nèi)容:用GPT生成文本后,填充到JSON的
text
字段。 - 可視化樣式:將JSON數(shù)據(jù)渲染為網(wǎng)頁(yè)或圖表,用于PPT設(shè)計(jì)預(yù)覽。
通過(guò)Python和JSON的結(jié)合,PPT的自動(dòng)化處理從未如此簡(jiǎn)單!
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 顏色轉(zhuǎn)換為十六進(jìn)制字符串(如 #FF0000)""" if rgb is None: return None return (rgb[0], rgb[1], rgb[2]) def parse_shape(shape): """解析單個(gè) 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): """解析整個(gè) PPT 文件并返回 JSON 結(jié)構(gòu)""" 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): """將解析后的數(shù)據(jù)保存為 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結(jié)構(gòu)詳解的詳細(xì)內(nèi)容,更多關(guān)于Python解析PPT并生成JSON的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python如何實(shí)現(xiàn)在字符串里嵌入雙引號(hào)或者單引號(hào)
今天小編就為大家分享一篇Python如何實(shí)現(xiàn)在字符串里嵌入雙引號(hào)或者單引號(hào),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03python實(shí)現(xiàn)接口并發(fā)測(cè)試腳本
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)接口并發(fā)測(cè)試腳本,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-06-06django在接受post請(qǐng)求時(shí)顯示403forbidden實(shí)例解析
這篇文章主要介紹了django在接受post請(qǐng)求時(shí)顯示403forbidden實(shí)例解析,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5表單布局控件QFormLayout詳細(xì)使用方法與實(shí)例
這篇文章主要介紹了python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5布局控件QFormLayout詳細(xì)使用方法與實(shí)例,需要的朋友可以參考下2020-03-03python環(huán)境的報(bào)錯(cuò)解決方法
這篇文章主要為大家介紹了python環(huán)境的報(bào)錯(cuò)解決方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08Python?Textual文本用戶界面庫(kù)使用原理探索
這篇文章主要為大家介紹了Python?Textual文本用戶界面框架使用原理探索,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-02-02python驗(yàn)證碼識(shí)別教程之利用投影法、連通域法分割圖片
這篇文章主要給大家介紹了關(guān)于python驗(yàn)證碼識(shí)別教程之利用投影法、連通域法分割圖片的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起看看吧2018-06-06Python使用struct處理二進(jìn)制(pack和unpack用法)
這篇文章主要介紹了Python使用struct處理二進(jìn)制(pack和unpack用法),幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-11-11