纯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 小时前
Python--04--数据容器(总结)
开发语言·python
架构师老Y2 小时前
008、容器化部署:Docker与Python应用打包
python·容器·架构
lifewange2 小时前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
pluvium273 小时前
记对 xonsh shell 的使用, 脚本编写, 迁移及调优
linux·python·shell·xonsh
2401_827499993 小时前
python项目实战09-AI智能伴侣(ai_partner_5-6)
开发语言·python
PD我是你的真爱粉3 小时前
MCP 协议详解:从架构、工作流到 Python 技术栈落地
开发语言·python·架构
ZhengEnCi3 小时前
P2G-Python字符串方法完全指南-split、join、strip、replace的Python编程利器
python
是小蟹呀^3 小时前
【总结】LangChain中工具的使用
python·langchain·agent·tool
宝贝儿好3 小时前
【LLM】第二章:文本表示:词袋模型、小案例:基于文本的推荐系统(酒店推荐)
人工智能·python·深度学习·神经网络·自然语言处理·机器人·语音识别
王夏奇4 小时前
pythonUI界面弹窗设置的几种办法
python·ui