[英]PPTX module - looping through paragraphs to find/replace text but only replaces 1st instance
I've been stuck on this for a while.我已经坚持了一段时间。 I'm using a find and replace function to loop through shape objects in Powerpoint using pptx module.我正在使用查找和替换 function 来使用 pptx 模块循环遍历 Powerpoint 中的形状对象。 When I call this function, it only replaces the 1st occurrence of the text (which happens to be the title).当我调用这个 function 时,它只替换了第一次出现的文本(恰好是标题)。 I suspect the issue is this current code ONLY replaces the first occurrence of the text or won't parse through the entire shape object and is looking for shapes that contain ONLY the full searchable text.我怀疑问题是当前代码仅替换了第一次出现的文本,或者不会解析整个形状 object 并且正在寻找仅包含完整可搜索文本的形状。
Code is found here: `代码可在此处找到:`
def search_and_replace(search_str, repl_str, input):
""""search and replace text in PowerPoint while preserving formatting"""
prs = Presentation(input)
for slide in prs.slides:
for shape in slide.placeholders:
print('%d %s' % (shape.placeholder_format.idx, shape.name))
if shape.has_text_frame:
if(shape.text.find(search_str))!=-1:
text_frame = shape.text_frame
cur_text = text_frame.paragraphs[0].runs[0].text
new_text = cur_text.replace(str(search_str), str(repl_str))
text_frame.paragraphs[0].runs[0].text = new_text
prs.save(input)
` `
I tried printing the shape objects and it looks like they are showing up properly.我尝试打印形状对象,看起来它们显示正确。
Don't forget text frames can have multiple paragraphs and runs不要忘记文本框可以有多个段落和运行
for paragraph in shape.text_frame.paragraphs:
for run in paragraph.runs:
I made my own module to replace text and images using pythonpptx.我制作了自己的模块来使用 pythonpptx 替换文本和图像。 It will do the hard part of replacing text runs for you: https://pypi.org/project/templatepptx/它将为您完成替换文本运行的困难部分: https://pypi.org/project/templatepptx/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.