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)
相关推荐
2301_790300962 分钟前
数据分析与科学计算
jvm·数据库·python
程序员小远16 分钟前
使用Postman进行一次完整的接口测试
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
Yvonne爱编码21 分钟前
JAVA数据结构 DAY1-集合和时空复杂度
java·数据结构·python
DN202027 分钟前
AI销售机器人:节日祝福转化率提升30倍
人工智能·python·深度学习·机器学习·机器人·节日
爱喝可乐的老王1 小时前
PyTorch简介与安装
人工智能·pytorch·python
看我干嘛!1 小时前
第三次python作业
服务器·数据库·python
deephub1 小时前
用 PyTorch 实现 LLM-JEPA:不预测 token,预测嵌入
人工智能·pytorch·python·深度学习·大语言模型
我的xiaodoujiao1 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 44--将自动化测试结果自动推送至钉钉工作群聊
前端·python·测试工具·ui·pytest
沈浩(种子思维作者)1 小时前
铁的居里点(770度就不被磁铁吸了)道理是什么?能不能精确计算出来?
人工智能·python·flask·量子计算
yufuu981 小时前
使用Scikit-learn进行机器学习模型评估
jvm·数据库·python