Replacing particular text in all sides of a ppt using python-pptx

Question:

I am new with python-pptx. But I am familiar with its basic working. I have searched a lot but I could not find a way to change a particular text by another text in all slides. That text may be in any text_frame of a slide. like all slides in a ppt have ‘java’ keyword, I want to change it by ‘python’ using python pptx in slides.

for slide in ppt.slides:
    if slide.has_text_frame:
        #do something with text frames
Asked By: tarun sahu

||

Answers:

Something like this should help, you’ll need to iterate the shape objects in each slide.shapes and check for a TextFrame and the existence of your keyword:

def replace_text_by_keyword(ppt, keyword, replacement):
    for slide in ppt.slides:
        for shp in slide.shapes:
            if shp.has_text_frame and keyword in shp.text:
                thisText = shp.text.replace(keyword, replacement)
                shp.text = thisText

This example is just a simple str.replace of course if you have more complicated replacement/text-updating algorithm, you can modify as needed.

Answered By: David Zemens

In addition when replacing text, you cannot simply replace it, you will loose all formatting.

Your text is contained in text_frame. Text_frame contain paragraphs, and paragraphs are made up of runs. A run contains all your formatting. You need to get to paragraph, then the run, then update text.

"A run exists to provide character level formatting, including font typeface, size, and color, an optional hyperlink target URL, bold, italic, and underline styles, strikethrough, kerning, and a few capitalization styles like all caps." (see reference below)

You’ll need to do something like this:

prs = Presentation('data/p1.pptx') 
for slide in prs.slides: 
    for shape in slide.shapes: 
        if not shape.has_text_frame: 
                continue 
        for paragraph in shape.text_frame.paragraphs:  
            for run in paragraph.runs:
                run.text=newText(run.text)                
prs.save('data/p1.pptx')

Official documentation(working with text): python-pptx.readthedocs.io
Visual representation of what this means Duplicate post

Answered By: Coder Dev
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.