纯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

相关推荐
爱滑雪的码农1 小时前
Java基础十一 流(Stream)、文件(File)和IO
java·开发语言·python
knight_9___1 小时前
LLM工具调用面试篇5
人工智能·python·深度学习·面试·职场和发展·llm·agent
小学生-山海1 小时前
YOLO火焰/烟雾检测系统
python·yolo
浔川python社1 小时前
浔川社团第一次福利数据公布
人工智能·python·deepseek
方也_arkling2 小时前
【大模型】初步认识RAG
人工智能·python
迁旭2 小时前
prompt_toolkit 3.0.52 API 参考手册
python
WL_Aurora2 小时前
Python 算法基础篇之堆和优先队列
python·算法
早日退休!!!2 小时前
PyTorch适配NPU
人工智能·pytorch·python
刀法如飞2 小时前
一款开箱即用的Flask 3.0 MVC工程脚手架,面向AI开发
后端·python·flask
xingpanvip2 小时前
星盘接口开发文档:组合三限盘接口指南
android·开发语言·前端·python·php·lua