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)
相关推荐
万行7 分钟前
机器学习&第一章
人工智能·python·机器学习·flask·计算机组成原理
2301_797312269 分钟前
学习java37天
开发语言·python
WJSKad123518 分钟前
果园树干识别与定位_faster-rcnn_x101-32x4d_fpn_1x_coco改进实践
python
深蓝电商API18 分钟前
Scrapy中间件实战:自定义请求头和代理池实现
python·scrapy·中间件
hui函数24 分钟前
Python系列Bug修复|如何解决 pip install 安装报错 invalid command ‘bdist_wheel’(缺少 wheel)问题
python·bug·pip
hui函数26 分钟前
Python系列Bug修复|如何解决 pip install -r requirements.txt 私有索引未设为 trusted-host 导致拒绝 问题
python·bug·pip
子午28 分钟前
【2026原创】动物识别系统~Python+深度学习+人工智能+模型训练+图像识别
人工智能·python·深度学习
o_insist33 分钟前
LangChain1.0 实现 PDF 文档向量检索全流程
人工智能·python·langchain
脑洞AI食验员38 分钟前
智能体来了:用异常与文件处理守住代码底线
人工智能·python
曲幽1 小时前
FastAPI登录验证:用OAuth2与JWT构筑你的API安全防线
python·fastapi·web·jwt·token·oauth2