纯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

相关推荐
阿童木写作6 小时前
跨境电商批量图片翻译与视频字幕翻译工具推荐
python·音视频
leihefeng6 小时前
手写数字识别:KNN vs 逻辑回归实战
python·算法·机器学习·逻辑回归·scikit-learn
SunnyDays10116 小时前
如何使用 Python 从 Word 文档中提取图片
python·word
2601_962097366 小时前
Pathway 实时RAG新方案:抛弃Spark、Flink,生产级数据管道
python·流处理·大数据集群·实时rag·pathway
三十岁老牛再出发6 小时前
9月3日总结
python
2601_962299887 小时前
Linux下运行Python脚本
linux·python·ubuntu·脚本·命令
IT毕设实战小研7 小时前
基于大数据的DAX40成分股金融新闻情感趋势可视化分析
android·大数据·python·考研·金融·课程设计
三十岁老牛再出发7 小时前
8月27日总结
python·pandas
砚底藏山河7 小时前
【量化纯GET实战 #21】用 pandas 做分析:把接口数据变成 DataFrame
java·python·金融·maven·pandas
Carl_奕然7 小时前
【智能体】Agent的四种设计模式之:React(2026最新版)
javascript·人工智能·python·react.js·设计模式·语言模型