如何使用python powerpoint保持文本的原始文本格式? [英] How to keep original text formatting of text with python powerpoint?

查看:109
本文介绍了如何使用python powerpoint保持文本的原始文本格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不更改格式的情况下更新文本框中的文本.换句话说,我想在更改文本时保持原始文本的原始格式

I'd like to update the text within a textbox without changing the formatting. In other words, I'd like to keep the original formatting of the original text while changing that text

我可以使用以下内容更新文本,但是在此过程中格式已完全更改.

I can update the text with the following, but the formatting is changed completely in the process.

from pptx import Presentation
prs = Presentation("C:\\original_powerpoint.pptx")
sh = prs.slides[0].shapes[0]
sh.text_frame.paragraphs[0].text = 'MY NEW TEXT'
prs.save("C:\\new_powerpoint.pptx")

如何在保持原始格式的同时更新文本?

How can I update the text while maintaining the original formatting?

我也尝试了以下方法:

from pptx import Presentation
prs = Presentation("C:\\original_powerpoint.pptx")
sh = prs.slides[0].shapes[0]
p = sh.text_frame.paragraphs[0]
original_font = p.font
p.text = 'NEW TEXT'
p.font = original_font

但是我遇到以下错误:

Traceback (most recent call last):
  File "C:\Codes\powerpoint_python_script.py", line 24, in <module>
    p.font = original_font
AttributeError: can't set attribute

推荐答案

文本框架由段落组成,而段落由运行组成.因此,您需要在运行中设置文本.

Text frame is consists of paragraphs and paragraphs is consists of runs. So you need to set text in run.

可能只有一次运行,您的代码可以像这样更改:

Probably you have only one run and your code can be changed like that:

from pptx import Presentation
prs = Presentation("C:\\original_powerpoint.pptx")
sh = prs.slides[0].shapes[0]
sh.text_frame.paragraphs[0].runs[0].text = 'MY NEW TEXT'
prs.save("C:\\new_powerpoint.pptx")

字符格式(字体特征)在运行时指定 等级.一个Paragraph对象包含一个或多个(通常是多个)运行. 分配给Paragraph.text时,该段中的所有运行都是 替换为一次新的运行.这就是为什么文本格式 消失因为包含该格式的运行会消失.

Character formatting (font characteristics) are specified at the Run level. A Paragraph object contains one or more (usually more) runs. When assigning to Paragraph.text, all the runs in the paragraph are replaced with a single new run. This is why the text formatting disappears; because the runs that contained that formatting disappear.

这篇关于如何使用python powerpoint保持文本的原始文本格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆