2024-Python-在做科研的时候遇见word里面的很多图片删除不了,那么我应该如何用程序操作呢

1.做科研的时候,下载word,全是别人的图,但是我不想要图,应该如何解决:

  • 每一页都是这样子的图,我不可能一个一个删除吧,
    在这里插入图片描述

2. 解决办法,直接看代码:

import zipfile
import os
import shutil
from xml.etree import ElementTree as ET

def remove_images_from_docx(docx_path, output_path):
    temp_dir = "temp_docx"
    with zipfile.ZipFile(docx_path, 'r') as docx_file:
        docx_file.extractall(temp_dir)
    
    document_xml_path = os.path.join(temp_dir, "word", "document.xml")
    
    tree = ET.parse(document_xml_path)
    root = tree.getroot()
    
    namespaces = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}

    # 遍历文档寻找包含图片的<w:drawing>元素
    # 由于没有getparent()方法,我们需要采用不同的策略来移除元素
    for parent in root.findall('.//w:drawing/..', namespaces):
        for child in list(parent):
            if child.tag.endswith('drawing'):
                parent.remove(child)

    tree.write(document_xml_path)
    
    media_dir = os.path.join(temp_dir, "word", "media")
    if os.path.exists(media_dir):
        for file in os.listdir(media_dir):
            os.remove(os.path.join(media_dir, file))
    
    with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as docx_out:
        for root, dirs, files in os.walk(temp_dir):
            for file in files:
                file_path = os.path.join(root, file)
                arcname = os.path.relpath(file_path, temp_dir)
                docx_out.write(file_path, arcname)
    
    shutil.rmtree(temp_dir)

# 调用函数
remove_images_from_docx('path_to_your_input.docx', 'path_to_your_output.docx')

Ok,完美

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值