如何使用 python powerpoint 保持文本的原始文本格式?

2022-01-12 00:00:00 python powerpoint python-pptx formatting

问题描述

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

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

从 pptx 导入演示文稿prs = Presentation("C:\original_powerpoint.pptx")sh = prs.slides[0].shapes[0]sh.text_frame.paragraphs[0].text = '我的新文本'prs.save("C:\new_powerpoint.pptx")

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

我还尝试了以下方法:

从 pptx 导入演示文稿prs = Presentation("C:\original_powerpoint.pptx")sh = prs.slides[0].shapes[0]p = sh.text_frame.paragraphs[0]original_font = p.fontp.text = '新文本'p.font = original_font

但是我得到以下错误:

Traceback(最近一次调用最后一次):文件C:Codespowerpoint_python_script.py",第 24 行,在 <module>p.font = original_fontAttributeError:无法设置属性

解决方案

文本框架由段落组成,段落由运行组成.所以你需要在运行中设置文本.

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

从 pptx 导入演示文稿prs = Presentation("C:\original_powerpoint.pptx")sh = prs.slides[0].shapes[0]sh.text_frame.paragraphs[0].runs[0].text = '我的新文本'prs.save("C:\new_powerpoint.pptx")

<块引用>

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

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?

I've also tried the following:

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

However I get the following error:

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

解决方案

Text frame consists of paragraphs and paragraphs 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")

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.

相关文章