Pythonのpython-pptx
ライブラリを使用して、PowerPointのテキストを置換する方法について説明します。
python-pptxとは
python-pptx
はPythonのライブラリで、Microsoft PowerPointのファイルを操作することができます。このライブラリを使用すると、新しいプレゼンテーションを作成したり、既存のプレゼンテーションを読み込んで編集したりすることができます。
テキストの置換
python-pptx
を使用してPowerPointのテキストを置換するには、以下の手順を実行します。
Presentation
クラスを使用してPowerPoint PPT/PPTXをロードします。Presentation.slides
コレクションを使用してスライドをループします。- 各反復で、
SlideUtil.get_all_text_boxes(slide)
メソッドを使用してスライドのテキストフレームを取得します。 - テキストフレームをループし、各反復で次の操作を実行します。
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のテキストを操作するための強力なツールであり、プレゼンテーションの自動生成や編集に役立ちます。