【Python】PowerPointから文章を読み込んで出力する方法(本文、プロパティ)

スポンサーリンク

Pythonを使用して、PowerPointファイルを読み込んで、本文、プロパティを出力する方法を紹介します。

やり方

1.以下コマンドででPowerPoint用のライブラリをインストール

pip install python-pptx

2.PowerPointファイルを作成し、適当な内容を記載する。今回は以下(“sample.pptx”というファイル名にした)

2.”sample.py”というファイルを作成し、以下を記載

# 「pip install python-pptx」を事前にインストール
import pptx

powerPoint = pptx.Presentation('sample.pptx')

properties = powerPoint.core_properties

print('--------プロパティ情報--------')

print(f'作成者: {properties.author}')
print(f'カテゴリ: {properties.category}')
print(f'コメント: {properties.comments}')
print(f'キーワード: {properties.keywords}')
print(f'最終編集者: {properties.last_modified_by}')
print(f'件名: {properties.subject}')
print(f'タイトル: {properties.title}')
print(f'文書の作成日時: {properties.created}')
print(f'文書の最終印刷日時: {properties.last_printed}')
print(f'文書の編集日時: {properties.modified}')

print('--------各スライドのテキスト--------')

for i, slide in enumerate(powerPoint.slides):
    print(f'■{i+1}枚目のスライド')
    # 図形を取得(図形の中にテキストはあるため)
    for shape in slide.shapes:
        # 図形の中にテキストがなければ、次の図形へ
        if not shape.has_text_frame:
            continue

        # テキストがある場合、テキストを出力
        for paragraph in shape.text_frame.paragraphs:
            print(paragraph.text)

3.以下のようにしてコマンドプロンプト等でファイルを実行(sample.pyはC:\work\python配下に配置)

C:\work\python> python .\sample.py

4.以下が出力される。

--------プロパティ情報--------
作成者: Microsoft アカウント
カテゴリ:
コメント:
キーワード:
最終編集者: Microsoft アカウント
件名:
タイトル: 1枚目のスライドタイトル
文書の作成日時: 2025-03-19 14:16:27
文書の最終印刷日時: None
文書の編集日時: 2025-03-19 14:17:26
--------各スライドのテキスト--------
■1枚目のスライド
1枚目のスライドタイトル
1枚目サブタイトル
■2枚目のスライド
2枚目スライドタイトル
2枚目本文

コメント

タイトルとURLをコピーしました