纯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

相关推荐
心之伊始2 小时前
Java synchronized 锁升级全过程深度解析:从 Mark Word 到偏向锁、轻量级锁与重量级锁的 HotSpot 实现
java·开发语言·word
谅望者2 小时前
数据分析笔记08:Python编程基础-数据类型与变量
数据库·笔记·python·数据分析·概率论
mortimer2 小时前
【实战复盘】 PySide6 + PyTorch 偶发性“假死”?由多线程转多进程
pytorch·python·pyqt
清静诗意2 小时前
Django REST Framework(DRF)RESTful 最完整版实战教程
python·django·restful·drf
studytosky2 小时前
深度学习理论与实战:Pytorch基础入门
人工智能·pytorch·python·深度学习·机器学习
长不大的蜡笔小新3 小时前
手写数字识别:从零搭建神经网络
人工智能·python·tensorflow
前进的李工3 小时前
LeetCode hot100:094 二叉树的中序遍历:从递归到迭代的完整指南
python·算法·leetcode·链表·二叉树
ins_lizhiming4 小时前
在华为910B GPU服务器上运行DeepSeek-R1-0528模型
人工智能·pytorch·python·华为
bwz999@88.com4 小时前
win10安装miniforge+mamba替代miniconda
python