LoginSignup
2
9

PythonでPowerPointからテキストを抽出する!(テーブルにも対応)

Last updated at Posted at 2020-12-29

##この記事について

会議の議事録などをメールで送る場合、スライドの文字だけ欲しい場合があったので、ちょっとコードを書いてみました。テーブルの文字を抜き出すのが若干手間でした。

##準備したPowerPointサンプルファイル (sampleFile.pptx として同じフォルダに入れておく)
スクリーンショット 2020-12-29 195938.png

##結果

File name:  sampleFile.pptx 

-- Page 1 --
タイトルです

サブタイトルです

-- Page 2 --
2ページ目です。
テキストボックスです♪

果物, 八百屋さんA, スーパーB, 
バナナ, 100円, 200円, 
リンゴ, 150円, 140円, 

テーブルのサンプル

##コード


import pptx
from glob import glob

for fname in glob ('*.pptx'):
    print ('File name: ', fname, '\n')
    prs = pptx.Presentation(fname)

    for i, sld in enumerate(prs.slides, start=1):

        print(f'-- Page {i} --')

        for shp in sld.shapes:
            
            if shp.has_text_frame:
                print (shp.text.replace('\n', ''))

            if shp.has_table:
                tbl = shp.table
                row_count = len(tbl.rows)
                col_count = len(tbl.columns)
                for r in range(0, row_count):                 
                    text=''
                    for c in range(0, col_count):
                        cell = tbl.cell(r,c)
                        paragraphs = cell.text_frame.paragraphs 
                        for paragraph in paragraphs:
                            for run in paragraph.runs:
                                text+=run.text.replace('\n', '')
                            text+=', '
                    print (text)
            print ()

同じフォルダに入っているpptxの拡張子が入っているファイルすべてのテキストを抽出します。

## 参考

Powerpoint(pptx)の表をスクレイピング
https://qiita.com/barobaro/items/a3a4a00aeda9d19e41b6

PDF・Word・PowerPoint・Excelファイルからテキスト部分を一括抽出するメソッド
https://qiita.com/barobaro/items/a3a4a00aeda9d19e41b6

2023/5/16

textの改行を省くよう、replace('\n', '')を追加しました。

2
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
9