pythonpresentationpython-pptx

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


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

Solution

  • 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.