0
2

More than 1 year has passed since last update.

python-pptxで テキストの見た目を保持しつつ文字を変更する

Last updated at Posted at 2022-12-27

結論

import pptx, re
from pptx.util import Cm, Pt, Inches

self.replace_text('置き換えられる文字列', '置き換える文字列')

def replace_text(self, before, after):
    for shp in self.slide.shapes:
        if shp.has_text_frame:
            if before in shp.text:
                new_text = re.sub(before, after, shp.text)
                    self.replace_paragraph_text_retaining_initial_formatting(shp.text_frame.paragraphs[0], new_text)

def replace_paragraph_text_retaining_initial_formatting(self, paragraph, new_text):
    p = paragraph._p
    for idx, run in enumerate(paragraph.runs):
        if idx > 0:
            p.remove(run._r)

    paragraph.runs[0].text = new_text

参考元のコードだとforループの処理がうまく行われていなかったため修正

参考

0
2
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
0
2