はじめに
自然言語処理のAI案件に関わっていると、ファイルに記述されている文字列を抽出して利用したい時があります。ファイル数や文字列の量が少なければ手動でコピペをすれば良いのですが、大量に扱う時は、堪ったものではありません。そんな時は、ツールを使えば簡単に短時間でファイル中の全文字列を抽出することが出来ます。今回はPPT&Excelの文字抽出ツールをご紹介します。
PPTツールについて
サンプルコード
PPTの文字抽出は、pptxパッケージのPresentationsを使います。
サンプルコードはこちらになります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# PowerPoint from pptx import Presentation def get_all_text(filepath: str): presentation = Presentation(filepath) results = [] for slide in presentation.slides: for shape in slide.shapes: # 文字列以外は飛ばす if not shape.has_text_frame: continue for par in shape.text_frame.paragraphs: for run in par.runs: # 全角スペースを削除 text = run.text.replace('\u3000', '') results.append(text) resultsStr = ''.join(results).replace('。','\n') print(resultsStr) get_all_text("./sample.pptx") |
ツール実行および結果
sample.pptxを用意して、実際に文字抽出できるか確認します。
![PPTXサンプル](https://alb-owned-https-576747877.ap-northeast-1.elb.amazonaws.com/wp-content/uploads/2021/02/sample_pptx-660x365.png)
実行してみます。
![PPTXサンプル実行](https://alb-owned-https-576747877.ap-northeast-1.elb.amazonaws.com/wp-content/uploads/2021/02/sample_pptx_execute.png)
みごと文字抽出ができました。
Excelツールについて
サンプルコード
Excelの文字抽出は、openpyxlパッケージを使います。
サンプルコードはこちらになります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# # Excel import openpyxl def print_excel_data(filepath: str): # ブックを取得 book = openpyxl.load_workbook(filepath) # シートを取得 sheetnames = book.sheetnames for sheetname in sheetnames: sheet = book[sheetname] results = [] # セル番地を取得 for cells in tuple(sheet.rows): for cell in cells: if cell.value != None: # 全角スペースを削除 text = str(cell.value).replace('\u3000', '') results.append(text) resultsStr = ''.join(results).replace('。','\n') print(resultsStr) print_excel_data("./sample.xlsx") |
ツール実行および結果
sample.xlsxを用意して、実際に文字抽出できるか確認します。(sheet1とsheet2を用意します。)
実行してみます。
![EXCELサンプル実行](https://alb-owned-https-576747877.ap-northeast-1.elb.amazonaws.com/wp-content/uploads/2021/02/sample_excel_execute.png)
みごと文字抽出ができました。
まとめ
ファイルの文字抽出をするpythonツールをご紹介しました。ファイル毎に実行するツールでしたが、もっと大量のファイルを扱う場合は、処理の初めに複数のファイルパスを配列に格納して、ループ処理でツールを実行する作りにしても良いと思います。
掲載したサンプルコードをコピペして、ご自身の状況に合わせてカスタマイズして使ってみてください。
執筆者プロフィール
![Akahori Yuu](https://alb-owned-https-576747877.ap-northeast-1.elb.amazonaws.com/wp-content/uploads/2018/07/5c4d0a84b1a861b2da148f0405d84a4c-500x280.jpg)
- tdi AI&データマネジメント推進部
- 配属当初はインフラエンジニア。ちょっと前に、ブロックチェーン(HyperledgerFabric)の案件にも参画。今はIBM Watsonを軸に、コンサルタント・開発を行っています。