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)
相关推荐
m0_7335654614 小时前
HTML函数开发需要独立显卡吗_HTML函数与显卡关系详解【说明】
jvm·数据库·python
2401_8844541514 小时前
Python测试代码如何实现自解释_使用pytest描述性命名规范
jvm·数据库·python
dinglu1030DL14 小时前
Go语言怎么格式化时间_Go语言time.Format教程【详解】
jvm·数据库·python
m0_6245785914 小时前
SQL数据分析如何剔除极端异常值_配合窗口函数检测偏离度
jvm·数据库·python
码农学院14 小时前
itextsharp .net中如何设置两个表格的间距设为0,取网站的域名,协议、端口、当前站点目录的地址
开发语言·c#·.net
川冰ICE14 小时前
Python爬虫实战⑱|Pandas分组聚合,一键生成统计报表
爬虫·python·pandas
宠..14 小时前
VS Code 修改 C++ 标准同时修改错误检测标准
java·linux·开发语言·javascript·c++·python·qt
2401_8800714014 小时前
Redis怎样查询集群的整体健康状态_使用cluster info指令查看槽位覆盖率与节点状态
jvm·数据库·python
2301_8159019714 小时前
Go语言如何写负载均衡器_Go语言负载均衡器实战教程【完整】
jvm·数据库·python
dFObBIMmai14 小时前
Redis怎样定位每秒被高频访问的热点键
jvm·数据库·python