【问题标题】:Replacing particular text in all sides of a ppt using python-pptx使用 python-pptx 替换 ppt 各方面的特定文本
【发布时间】:2018-06-21 07:32:16
【问题描述】:

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

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

【问题讨论】:

    标签: python presentation python-pptx


    【解决方案1】:

    这样的事情应该会有所帮助,您需要在每个 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当然如果你有更复杂的替换/文本更新算法,你可以根据需要进行修改。

    【讨论】:

    • 仅供参考,这会降低文本对齐方式
    【解决方案2】:

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

    您的文本包含在 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-22
      • 1970-01-01
      • 2019-11-07
      • 2017-09-08
      • 1970-01-01
      • 2012-12-12
      • 2016-10-21
      • 2015-06-22
      相关资源
      最近更新 更多