纯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

相关推荐
qq_417695051 天前
机器学习与人工智能
jvm·数据库·python
漫随流水1 天前
旅游推荐系统(view.py)
前端·数据库·python·旅游
yy我不解释1 天前
关于comfyui的mmaudio音频生成插件时时间不一致问题(一)
python·ai作画·音视频·comfyui
紫丁香1 天前
AutoGen详解一
后端·python·flask
FreakStudio1 天前
不用费劲编译ulab了!纯Mpy矩阵micronumpy库,单片机直接跑
python·嵌入式·边缘计算·电子diy
清水白石0081 天前
Free-Threaded Python 实战指南:机遇、风险与 PoC 验证方案
java·python·算法
飞Link1 天前
具身智能核心架构之 Python 行为树 (py_trees) 深度剖析与实战
开发语言·人工智能·python·架构
桃气媛媛1 天前
Pycharm常用快捷键
python·pycharm
Looooking1 天前
Python 之获取安装包所占用磁盘空间大小
python
WenGyyyL1 天前
ColBERT论文研读——NLP(IR)里程碑之作
人工智能·python·语言模型·自然语言处理