亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

使用Python解析PPT文件并生成JSON結(jié)構(gòu)詳解

 更新時(shí)間:2025年04月29日 10:49:26   作者:東方佑  
PowerPoint(PPT)文件的自動(dòng)化處理是辦公自動(dòng)化和數(shù)據(jù)提取的常見(jiàn)需求,本文將介紹如何通過(guò)Python的python-pptx庫(kù),將PPT文件的樣式、結(jié)構(gòu)、文本內(nèi)容等信息解析為標(biāo)準(zhǔn)化的JSON格式,為后續(xù)的自動(dòng)化處理、數(shù)據(jù)遷移或樣式復(fù)用提供基礎(chǔ),需要的朋友可以參考下

核心代碼解析

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)、位置(lefttop)、尺寸(widthheight)。
  • 填充樣式:顏色類型(純色/漸變)、顏色值(十六進(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_BOX1文本框
MSO_SHAPE_TYPE.TABLE19表格
MSO_SHAPE_TYPE.PICTURE17圖片
其他形狀根據(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)

  1. 單位轉(zhuǎn)換

    • PPT中的尺寸單位為EMU(English Metric Unit),可通過(guò)shape.width/9525轉(zhuǎn)換為像素(1 EMU ≈ 0.01像素)。
  2. 異常處理

    • 部分形狀可能無(wú)文本框(如圖片),需通過(guò)shape.has_text_frame判斷。
    • 顏色值可能為None(如填充為透明色),需設(shè)置默認(rèn)值。
  3. 擴(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)文章

最新評(píng)論