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)
相关推荐
hez201011 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
databook12 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室12 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三14 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271117 小时前
Python之语言特点
python
刘立军18 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机21 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python