今天来学习如何自动读取PPT中的文字并保存到Word中
首先,了解PPT的构架是如何的
将 PPT 中的结构按照层级关系来排列是这样的:
幻灯片页 -> 形状 -> 文本框 -> 段落 -> 样式块
了解了 PPT 文件的基础结构后,接下来就要使用 Python 读取内容。
首先,我们要安装 python-pptx 模块,它可以读取和修改 .pptx 文件,不支持 .ppt 文件。
通过代码
pip install python-pptx 在终端上进行安装。
如果在自己电脑上安装不上或安装缓慢,可在命令后添加
pip install python-pptx -i https://pypi.tuna.tsinghua.edu.cn/simple/
然后,输入以下代码
# 使用from...import从pptx模块中导入Presentation
from pptx import Presentation
# 使用import导入docx
import docx
# 新建一个空白Word文档,赋值给变量docxFile
docxFile = docx.Document()
# 将.pptx文件路径赋值给变量path
path = r"D:\001studymaterial\statistics.pptx"
# 读取path并赋值给变量pptxFile
pptxFile = Presentation(path)
# TODO 将变量n设置为1
n = 1
# for循环遍历pptxFile中的.slides属性,赋值给slide
for slide in pptxFile.slides:
# TODO 向文档中添加标题f"第{n}页",为二级标题
docxFile.add_heading(f"第{n}页",level=2)
# for循环遍历slide中.shapes属性,赋值给变量shape
for shape in slide.shapes:
# 判断形状中是否有文本框
if shape.has_text_frame == True:
# 读取形状中的文本框,并赋值给变量textFrame
textFrame = shape.text_frame
# for循环遍历文本框内的所有段落
# 赋值给变量paragraph
for paragraph in textFrame.paragraphs:
# for循环遍历段落中的所有样式块
# 赋值给变量run
for run in paragraph.runs:
# 读取样式块中的文本内容
texts = run.text
# 向Word文档中添加段落texts的文本内容
docxFile.add_paragraph(texts)
# TODO 将变量n进行累加
n = n+1
# 保存文档到指定路径,并命名为"资料.docx"
docxFile.save(r"D:\001studymaterial\stata.docx")
真不错,学会了这段代码,以后看PPT都是别人的两倍速啦!