纯Python 实现 Word 文档转换 Markdown

python 复制代码
# 读取 Word 文件
from datetime import time  # 这会导入datetime模块的time类
import uuid
import mammoth
from markdownify import markdownify


    # 转存 Word 文档内的图片
def convert_img(image):
    with image.open() as image_bytes:
        file_suffix = image.content_type.split("/")[1]
        # 使用UUID生成唯一文件名,避免时间戳冲突
        filename = f"{uuid.uuid4().hex}.{file_suffix}"
        path_file = f"./img/{filename}"

        # 确保img目录存在
        import os
        os.makedirs("./img", exist_ok=True)

        with open(path_file, 'wb') as f:
            f.write(image_bytes.read())

    return {"src": path_file}
with open(r"1导读.docx" ,"rb") as docx_file:
    # 转化 Word 文档为 HTML
    result = mammoth.convert_to_html(docx_file,convert_image=mammoth.images.img_element(convert_img))
    # 获取 HTML 内容
    html = result.value
    # 转化 HTML 为 Markdown
    md = markdownify(html,heading_style="ATX")
    print(md)
    with open("./docx_to_html.html",'w',encoding='utf-8') as html_file,open("./docx_to_md.md","w",encoding='utf-8') as md_file:
        html_file.write(html)
        md_file.write(md)
    messages = result.messages

这是原始数据test.docx

相关推荐
向量引擎11 小时前
[硬核架构] 2026 企业级 AI 网关落地指南:从“连接超时”到“秒级响应”的架构演进(附 Python/Java 源码)
人工智能·python·gpt·ai作画·架构·aigc·api调用
0思必得011 小时前
[Web自动化] Selenium模拟用户的常见操作
前端·python·selenium·自动化
凡客丶11 小时前
Windows版Miniconda打包环境迁移到内网离线环境【详解】
windows·python
AI大佬的小弟11 小时前
【详细步骤】大模型基础知识(4)---ollama模型调用-多轮对话体验
python·ollama·大模型基础·ai 聊天机器人·简单的大模型部署·实现ollama模型调用·零基础上手 ollama体验
AndrewHZ11 小时前
【Python与生活】怎么用python画出好看的分形图?
开发语言·python·生活·可视化·递归·分形
sweden_dove11 小时前
《python编程练习题》中的第二部分内容(19-36)和第三部分内容(37-54)
开发语言·python
skywalk816312 小时前
FreeBSD下安装rustup、cargo和uv
开发语言·python·rust·cargo
GDAL12 小时前
Python pip 全面讲解教程(2026 实用版)
python·pip
WangYaolove131412 小时前
基于人脸表情的分类算法的设计(源码+文档)
python·mysql·django·毕业设计·源码