Pythonのpython-pptxライブラリを使用して、PowerPointのテキストを置換する方法について説明します。

python-pptxとは

python-pptxはPythonのライブラリで、Microsoft PowerPointのファイルを操作することができます。このライブラリを使用すると、新しいプレゼンテーションを作成したり、既存のプレゼンテーションを読み込んで編集したりすることができます。

テキストの置換

python-pptxを使用してPowerPointのテキストを置換するには、以下の手順を実行します。

  1. Presentationクラスを使用してPowerPoint PPT/PPTXをロードします。
  2. Presentation.slidesコレクションを使用してスライドをループします。
  3. 各反復で、SlideUtil.get_all_text_boxes(slide)メソッドを使用してスライドのテキストフレームを取得します。
  4. テキストフレームをループし、各反復で次の操作を実行します。
import pptx, re
from pptx.util import Cm, Pt, Inches

def replace_paragraph_text_retaining_initial_formatting(paragraph, new_text):
    p = paragraph._p # the lxml element containing the <a:p> paragraph element
    # remove all but the first run
    for idx, run in enumerate(paragraph.runs):
        if idx == 0:
            continue
        p.remove(run._r)
    paragraph.runs[0].text = new_text

prs = pptx.Presentation("元のファイル.pptx")
slide=prs.slides[0] #先頭のページを選択
for shp in slide.shapes:
    if shp.has_text_frame:
        if "日付は" in shp.text: #変更する文字列の一部でマッチさせる
            new_text=re.sub('。。。', '2021年3月6日', shp.text) #置き換え
            replace_paragraph_text_retaining_initial_formatting(shp.text_frame.paragraphs[0], new_text)
prs.save('変更後のファイル.pptx')

このコードは、指定されたテキストのすべての出現を別のテキストに置き換えます。

まとめ

python-pptxライブラリを使用すると、PythonからPowerPointのテキストを効率的に置換することができます。このライブラリは、PowerPointのテキストを操作するための強力なツールであり、プレゼンテーションの自動生成や編集に役立ちます。

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です