使用 python-pptx 替换 ppt 四周的特定文本

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

我是 python-pptx 的新手。但我熟悉它的基本工作原理。我搜索了很多,但找不到在所有幻灯片中用另一个文本更改特定文本的方法。该文本可能位于幻灯片的任何 text_frame 中。就像 ppt 中的所有幻灯片都有 'java' 关键字一样,我想通过 'python' 在幻灯片中使用 python pptx 来更改它。

for slide in ppt.slides:
    if slide.has_text_frame:
        #do something with text frames

这样的事情应该有所帮助,您需要迭代每个 slide.shapes 中的 shape 对象并检查 TextFrame 和您的关键字是否存在:

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

这个例子只是一个简单的例子str.replace当然如果你有更复杂的replacement/text-updating算法,你可以根据需要修改

另外在替换文字的时候,不能简单的替换,会丢失所有的格式。

您的文字包含在 text_frame 中。 Text_frame 包含段落,段落由 运行 组成。 运行 包含您的所有格式。您需要转到段落,然后是 运行,然后更新文本。

"存在 运行 以提供字符级格式设置,包括字体、大小和颜色、可选的超链接目标 URL、粗体、斜体和下划线样式、删除线、字距调整和一些大写样式,例如全部大写。"请参阅下面的参考资料

您需要执行以下操作:

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')

官方文档(使用文本):python-pptx.readthedocs.io
这意味着什么的直观表示 Duplicate post