我有一个演讲。该演示文稿包含一张带有文本框架的幻灯片。 文本是:“测试变量_变体”。
我导入演示文稿并浏览幻灯片的形状。 我想获取形状的文本。然后为变量“variable_variant”输入一个字符串。 例如:如果variant_variant =“version5”,代码应将形状的文本更改为“Tested version5”。 形状的位置和文字的大小应该相同。
这是我的代码的一部分:
对于值中要替换的 string_to_replace: 如果 shape.text 中的 string_to_replace : 文本 = 形状.文本 text_neu = text.replace(要替换的字符串,值[要替换的字符串]) 文本框 = 形状.文本框 text_frame.clear() p = text_frame.paragraphs[0] p.text = text_neu
正确替换了文字,但替换后字母大小不同。
我尝试获取文本框的大小并将其放在替换后的文本框上。 如果我尝试使用 font.size 阅读,它不会返回任何内容...
在我的演示中使用以下方法解决了这个问题:
def update_text(slide_number, shape_name, old_text, new_text):
# presentation = Presentation(pptx_file) is already instantiated slide = presentation.slides[slide_number - 1]
for shape in slide.shapes:
if not shape.has_text_frame: # Check if the shape object contains a TextFrame
continue
else:
print(shape.name) # >> Title 1, Text box 3, Arrows: right 4, Callout: circular 12 <- this is debug part, remove it when done
if shape.name == shape_name:
if shape.has_text_frame:
# my debug checks - remove when done
print("Updating old: " + shape.text)
print(shape.text_frame.text)
# print(str(shape.text_frame.text.font.name))
# Iterate through paragraphs and runs to find and replace the text preserving the format
for paragraph in shape.text_frame.paragraphs:
for run in paragraph.runs:
if old_text in run.text:
updated_text = run.text.replace(old_text, new_text)
run.text = updated_text
print("With the new: " + str(new_text))