Python将md批量转为docx

这两天写毕业论文, 发现了一个可以将markdown快速转为word格式的小工具pandoc, 非常好用, 比如我有一个名为毕业论文.md的文件, 我只需在命令行运行

pandoc 毕业论文.md -o 毕业论文.docx

即可根据md文件生成新的docx文件!

pandoc支持相互转换的格式, 多的惊人!
3203841-229cb26008a222b8.jpg
pandoc

Pandoc主站链接

3203841-d0a5944b49ccf0d7.png

安装包下载地址

3203841-494db34c2d9b4049.png
https://github.com/jgm/pandoc/releases/tag/2.2

使用技巧:

  • 由于word确实很难用, 我们可以用md格式书写, 然后转换成docx
  • 懒是第一生产力, pandoc可以在命令行运行, 所以, 我们可以配合python脚本将md格式批量转换为docx
  • 这是我写的一个简易脚本
import os  

def auto_md_to_docx(file_dir):
    # 获取当前目录下所有的md文件的路径信息
    all_whole_path_files = []
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            try:
                if file[-3:] == ".md":
                    file_info = [root+'/', file]
                    all_whole_path_files.append(file_info)
            except Exception as e:
                print(e)
    print("==>", all_whole_path_files)

    # 将md依次转换为pandoc
    for file_info in all_whole_path_files:
        md_file_path_file = file_info[0] + file_info[1]
        docx_file_name = file_info[1][:-3] + '.docx'
        docx_file_path_file = file_info[0] + docx_file_name
        new_command = 'pandoc ' + md_file_path_file + ' -o ' + docx_file_path_file

        try:
            result = os.popen(new_command).readlines()
            if len(result) == 0:
                print(md_file_path_file, "已经转换为", docx_file_path_file)
        except Exception as e:
            print(e)

def main():
    auto_md_to_docx('.')

if __name__ == '__main__':
    main()


3203841-33d9cccd39c637d7.png
运行效果

3203841-714b3b8df970e0a0.png
最终结果

windows用户安装pandoc

1.下载32位免安装版软件包

下载地址: https://github.com/jgm/pandoc/releases/tag/2.2.1

3203841-c468f8a67a7cbc8d.png
2.将软件包放入c盘, 并解压
3203841-7e1464c1d5834613.png
3.获取pandoc.exe的绝对路径
3203841-113fa740b3b49ead.png
4. 将pandoc.exe的绝对路径放入环境变量
3203841-68e8dc2844adf6b4.png
3203841-5f28bdc7c5c5d47a.png
3203841-728ab3c40b1e57e3.png
3203841-c15a9de6f309dca0.png
3203841-f1f3d12d6825853a.png
3203841-1109863c47aac78c.png
  • 值得一提的是, 我这里用的md测试文件, 都是从我的简书后台打包下载的, 也就是本地是不存在图片的, 而pandoc会自动帮我们把图片下载到本地, 然后保存到新生成的doc中.
  • 只要将我的脚本稍加修改, 就可以按照上面的网状图, 进行任意两种格式的互转(比如word转pdf), 有兴趣的小伙伴可以自己动手折腾一下

另外, 小白福利, 我把这篇博客做成了视频 https://www.bilibili.com/video/av24136955/
欢迎观看, 欢迎投币, 欢迎弹幕, 欢迎转发,,,

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值