纯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

相关推荐
再渊23 分钟前
基因归因到底怎么计算的?
python·深度学习·机器学习
E_ICEBLUE32 分钟前
Python 拆分 Excel 文件:使用 Spire.XLS 实现按工作表、行、列和条件拆分
python·excel
aiqianji44 分钟前
有哪些稳定的AI短篇小说写作软件可以推荐?
人工智能·python
Ulyanov1 小时前
Python雷达电子对抗仿真引擎(一):打破单体瓶颈,构建微服务与ECS架构的顶层设计
开发语言·python·微服务·云原生·架构·雷达电子对抗
蓝创工坊Blue Foundry1 小时前
批量提取图片中的数字:怎样整理成一张可核对的 Excel
python·ai·ocr·excel·paddlepaddle
bug嘛我经常写1 小时前
如何批量删除word文档中存在的无用样式
经验分享·python·word
5G微创业2 小时前
Python / Node.js 调用短视频去水印 API 完整示例(含 SDK)
python·node.js·音视频·api·sdk·短视频
phltxy2 小时前
LangGraph智能租房助手实践
大数据·人工智能·python·深度学习·语言模型·langchain
码银2 小时前
放弃了豆包,我使用Python做了一个桌面宠物
python·microsoft·宠物
测功机之家3 小时前
国内口碑好的测功机公司找哪家
python·物联网