0

I'm trying to replace multiple substrings inside a text-frame on Python-PPTX (PowerPoint Presentation module). I'm using the 'replace' string method to do it, one-by-one but when I save the presentation I noticed that it did not replaced my substrings.

PS: I'm using '.paragraphs[0].runs[0]' to keep the original formatting.

The whole string is: "Realizado no dia XX, com duração de YY horas.\nSão Paulo, ZZ de mês de ano."

I'm trying to replace the substrings: 'XX', 'YY', 'ZZ', 'mês' and 'ano'

The code:

from pptx import Presentation
prs = Presentation(r'template.pptx')

for slide in prs.slides:
    for shape in slide.shapes:
        if shape.has_text_frame:
            if (shape.text.find('XX')) != -1:
                text_frame = shape.text_frame
                cur_text = text_frame.paragraphs[0].runs[0].text
                new_text = cur_text.replace('XX',day)
                new_text = new_text.replace('YY', '08')
                new_text = new_text.replace('ZZ', day)
                new_text = new_text.replace('mês',mes[int(mon)])
                new_text = new_text.replace('ano', '2021')
                text_frame.paragraphs[0].runs[0].text = new_text
prs.save('test.pptx')

Thanks

AlexMacabu
  • 127
  • 9

2 Answers2

0

Turns out that my string has two paragraphs and no runs. So I've stored each paragraph in its own variable and performed the substring replacement.

from pptx import Presentation
prs = Presentation(r'template.pptx')

for slide in prs.slides:
    for shape in slide.shapes:
        if shape.has_text_frame:
            if (shape.text.find('XX')) != -1:
                text_frame = shape.text_frame
                p1_text = text_frame.paragraphs[0].text 
                p2_text = text_frame.paragraphs[1].text
                new_p1 = p1_text.replace('XX',day)
                new_p1 = new_p1.replace('YY', '08')
                new_p2 = p2_text.replace('ZZ', day)
                new_p2 = new_p2.replace('mês',mes[int(mon)])
                new_p2 = new_p2.replace('ano', '2021')
                text_frame.paragraphs[0].text = new_p1
                text_frame.paragraphs[1].text = new_p2
prs.save('test.pptx')
AlexMacabu
  • 127
  • 9
  • This topic REALLY helped me to understand the problem https://stackoverflow.com/questions/45247042/how-to-keep-original-text-formatting-of-text-with-python-powerpoint – AlexMacabu Mar 30 '21 at 12:46
0
text = 'do it this way, and keep it up'

dict = {'this': 'that', 'up': 'down'}

def replace_multiple(document, amendment_dictionary):
  return [document := document.replace(change, amendment_dictionary[change]) for change in amendment_dictionary][len(amendment_dictionary)-1]

print(replace_multiple(text, dict))
Stevo
  • 248
  • 4
  • 8