Python将word文件转化为HTML文件和markdown文件

一、使用的主要模块

  • mammoth
  • markdownify
  • time
  • pathlib
  • os

二、代码

2.1 将word转变为HTML

def wordToHtml(filename):
    with open(filename+".docx", "rb") as docx_file:
        result = mammoth.convert_to_html(docx_file)
        with open(filename+".html", "w") as html_file:
            html_file.write(result.value)
# 支持word中存在图片

2.2 将word转变为MD

def wordToMd(filename):
    with open(filename+".docx", "rb") as docx_file:
        result = mammoth.convert_to_markdown(docx_file)
        with open(filename+".md", "w") as markdown_file:
            markdown_file.write(result.value)
# 不支持word中存在图片

2.3 支持word中有图片转为MD

def MD(filename):
    with open(filename+".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")
        with open("./docx_to_md.md", "w",encoding='utf-8') as md_file:
            # html_file.write(html)
            md_file.write(md)
        messages = result.messages

# 转存Word文档内的图片
def convert_img(image):
    with image.open() as image_bytes:
        file_suffix = image.content_type.split("/")[1]
        # word中图片转为的目录,如果不存在则新建
        my_img = Path("./img")
        if my_img.is_dir()==0:
            os.makedirs("img")
        path_file = "./img/{}.{}".format(str(time.time()),file_suffix)
        with open(path_file, 'wb') as f:
            f.write(image_bytes.read())
    return {"src":path_file}
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Joker_PL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值