Python提取Word中的所有图片

原理说明

.docx文件其实也就是一个压缩文件,当我们将一个.docx文件直接解压后可以看到_rels、docProps、word三个文件夹和文件[Content_Types].xml,其中我们要找的图片就在word/media目录内。因此,要提取word内的图片可以考虑将.docx文件解压,再从word/media文件内提取图片,最后将解压后的临时文件删除即可。

代码实现

完整代码

方法1

import zipfile
import os
import shutil

def word2img(word_path, result_path):
    tmp_path = f'{os.path.splitext(word_path)[0]}'
    splitext = os.path.splitext(word_path)
    zip_path = shutil.copy(word_path, f'{splitext[0]}_new{splitext[1]}')
    with zipfile.ZipFile(zip_path, 'r') as f:
        for file in f.namelist():
            f.extract(file, tmp_path)
    os.remove(zip_path)
    pic_path = os.path.join(tmp_path, 'word/media')
    if not os.path.exists(pic_path):
        shutil.rmtree(tmp_path)
        return 'no pictures found'
    pictures = os.listdir(pic_path)
    if not os.path.exists(result_path):
        os.makedirs(result_path)
    for picture in pictures:
        word_name = os.path.splitext(word_path)[0]
        if os.sep in word_name:
            new_name = word_name.split('\\')[-1]
        else:
            new_name = word_name.split('/')[-1]
        picture_name = f'{new_name}_{picture}'
        shutil.copy(os.path.join(pic_path, picture), os.path.join(result_path, picture_name))

    shutil.rmtree(tmp_path)
    return (os.path.join(result_path, pic) for pic in os.listdir(result_path))

方法2

  • 需要安装docx库:pip install docx
import os
import docx
import re

def word2img2(word_path, result_path):
    doc = docx.Document(word_path)
    dict_rel = doc.part._rels
    for rel in dict_rel:
        rel = dict_rel[rel]
        if "image" in rel.target_ref:
            if not os.path.exists(result_path):
                os.makedirs(result_path)
            img_name = re.findall("/(.*)", rel.target_ref)[0]
            word_name = os.path.splitext(word_path)[0]
            if os.sep in word_name:
                new_name = word_name.split('\\')[-1]
            else:
                new_name = word_name.split('/')[-1]
            img_name = f'{new_name}_{img_name}'
            with open(f'{result_path}/{img_name}', "wb") as f:
                f.write(rel.target_part.blob)

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值