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)

目前参考内容未直接提及使用Python提取Word文档中图片及其对应章节的方法,但可结合已有知识提供一种可能的实现思路。 可以使用`python-docx`库来读取Word文档,该库能访问文档中的文本和元素。通过遍历文档中的段落和运行对象,查找图片元素(在`python-docx`中,图片是以嵌入式对象形式存在)。对于章节的确定,可以根据文档的标题样式(如Heading 1、Heading 2等)来划分章节。 以下是一个示例代码: ```python import docx def extract_images_and_chapters(doc_path): doc = docx.Document(doc_path) current_chapter = None images_and_chapters = [] for para in doc.paragraphs: if para.style.name.startswith('Heading'): current_chapter = para.text for run in para.runs: if 'graphicData' in run._element.xml: # 这里只是简单记录图片和章节信息,实际保存图片还需要额外处理 images_and_chapters.append((run, current_chapter)) return images_and_chapters doc_path = 'your_document.docx' result = extract_images_and_chapters(doc_path) for image, chapter in result: print(f"图片所在章节: {chapter}") ``` ### 代码解释 1. **导入`docx`库**:用于读取Word文档。 2. **定义`extract_images_and_chapters`函数**:该函数接受Word文档的路径作为参数。 3. **遍历段落**:检查段落样式是否为标题样式,如果是则更新当前章节名称。 4. **遍历运行对象**:检查运行对象的XML中是否包含`graphicData`,如果包含则认为是图片元素,记录图片和对应的章节。 5. **返回结果**:返回包含图片和对应章节信息的列表。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值