python读取word文档,遍历每一个段落,查看其中有没有jpeg格式图片,如果有保存到硬盘,请给出代码
时间: 2024-05-11 11:16:09 浏览: 325
好的,以下是Python代码实现:
import os
import re
from docx import Document
# 读取word文档
document = Document('example.docx')
# 遍历每一个段落
for paragraph in document.paragraphs:
# 查找段落中的图片
for run in paragraph.runs:
# 判断run是否为图片,并且图片格式为jpeg
if run._element.xml.startswith('<w:drawing'):
if 'jpeg' in run._element.xml:
# 保存图片到硬盘
image_path = 'image/' + os.path.basename(document.filename).replace('docx', 'jpeg')
with open(image_path, 'wb') as f:
f.write(run.inline_pic.pic.nonce)
上面的代码使用docx
库读取word文档,在遍历每个段落时,再查找是否有图片,并判断图片格式是否为jpeg
,如果是,则保存到硬盘上的image
文件夹中。
相关推荐















