纯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

相关推荐
CryptoPP19 小时前
对接BSE交易所获取数据。
python·金融·数据挖掘·数据分析·区块链
老歌老听老掉牙19 小时前
PyQt5中RadioButton互斥选择的实现方法
开发语言·python·qt
Pyeako19 小时前
Opencv计算机视觉
人工智能·python·深度学习·opencv·计算机视觉
还不秃顶的计科生19 小时前
LeetCode 热题 100第一题:两数之和python版本
python·算法·leetcode
2401_8414956419 小时前
【Python高级编程】2026 丙午马年元旦祝福程序
python·动画·tkinter·程序·pyinstaller·元旦·turtle
该醒醒了~19 小时前
使用auto-py-to-exe打包python程序exe并添加图标和ico文件
python
idealzouhu19 小时前
【Android】深入浅出 JNI
android·开发语言·python·jni
兜兜转转了多少年19 小时前
《Python 应用机器学习:代码实战指南》笔记2 从0理解机器学习 —— 核心概念全解析
笔记·python·机器学习
reasonsummer19 小时前
【教学类-70-04】20251231小2班幼儿制作折纸方镜(八卦神兽镜)
python·通义万相
IT·小灰灰20 小时前
大模型API成本优化实战指南:Token管理的艺术与科学
人工智能·python·数据分析