Python使用总结之py-docx将word文件中的图片保存,并将内容返回

Python使用总结之py-docx将word文件中的图片保存,并将内容返回

使用py-docx读取word文档的内容,其中包含标题、文本和图片等信息。该方法将标题和内容返回,并将文件中的图片保存到指定的文件夹中。

实现步骤

  1. 加载文件内容
  2. 读取文件的段落
  3. 对文件段落做判断
  4. 根据判断结果进行数据保存或者文件保存

代码部分

python 复制代码
from docx import Document
import os
import re

def extract_images_and_text(doc_path, output_folder):
    # 判断文件是否存在
    os.makedirs(output_folder, exist_ok=True)

    # 获取文件内容
    doc = Document(doc_path)

    # 创建数据保存字典
    content_dict = {}

    # 保存文件标题
    title = doc.paragraphs[0].text.strip() if doc.paragraphs else "Untitled"

    # 导出文件内容和图片
    full_text = ""
    img_count = 0

    for para in doc.paragraphs:
        full_text += para.text + "\n"

    for rel in doc.part.rels:
        rel = doc.part.rels[rel]
        if "image" in rel.target_ref:
            img_count += 1
            img_data = rel.target_part.blob
            img_filename = f"image_{img_count}.png"
            img_path = os.path.join(output_folder, img_filename)

            with open(img_path, "wb") as img_file:
                img_file.write(img_data)

    # 清楚特殊符号
    content_dict[title] = re.sub(r'\n\s*\n', '\n', full_text.strip())

    return content_dict

# Example usage:
doc_path = "path/to/your/document.docx"
output_folder = "path/to/output/folder"
result = extract_images_and_text(doc_path, output_folder)
print(result)
相关推荐
weixin_449290012 分钟前
Python vs Go:优缺点对比
网络·python·golang
echome88812 分钟前
Python 上下文管理器详解:with 语句的优雅实践
python
大明者省14 分钟前
Python 程序在 Ubuntu 系统的完整部署流程
开发语言·python·ubuntu
智算菩萨15 分钟前
【Tkinter】14 事件处理机制深度解析:从基础绑定到高级传播,构建交互式绘图笔记应用
开发语言·笔记·python·microsoft·ui·ai编程·tkinter
SeatuneWrite15 分钟前
AI漫剧APP2025推荐,创意无限的个性化剧情体验
人工智能·python
财经资讯数据_灵砚智能16 分钟前
全球财经资讯日报(日间)2026年4月1日
大数据·人工智能·python·语言模型·ai编程
华科大胡子19 分钟前
Git二分法精准定位Bug
python
余衫马20 分钟前
在 IIS 部署 .NET6 WebApi 应用
运维·c#·iis·.net·发布
zero159723 分钟前
Python 8天极速入门笔记(大模型工程师专用):第六篇-函数进阶 + 模块导入,大模型实战调用前置
开发语言·python·大模型编程语言
无风听海25 分钟前
.NET10之C# File-Scoped Namespace 深度解析
c#·.net·.net10