Python将DOCX转换为markdown文件

需求驱动

我写了很多文章,用docx来保存,现在想把他放到博客上,我该怎么做?复制粘贴?不!我要格式转换!

DOCX转换成HTML

from pydocx import PyDocX
html = PyDocX.to_html(r"E:\工作管理\环境搭建\文档上传\格式转换\test.docx")
f = open("test.html", 'w', encoding="utf-8")
f.write(html)
f.close()

在这里插入图片描述如上图已经生成文件,我们看看效果:

在这里插入图片描述如上图,效果还是不错的。

HTML转换成markdown

from pydocx import PyDocX
import html2text as ht

html = PyDocX.to_html(r"E:\工作管理\环境搭建\文档上传\格式转换\test.docx")
f = open("test.html", 'w', encoding="utf-8")
f.write(html)
f.close()

text_maker = ht.HTML2Text()
text_maker.bypass_tables = False
path =r"E:\工作管理\环境搭建\文档上传\格式转换\test.html"
htmlfile = open(path,'r',encoding='UTF-8')
htmlpage = htmlfile.read()
text = text_maker.handle(htmlpage)
md = text.split('#') 
open("test.md","w").write(md[1]) 
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以使用Python的第三方库`pandoc`和`python-pptx`来实现将Markdown文件转换为PPT文件的功能。 首先需要安装这两个库,可以使用以下命令进行安装: ```bash pip install pandoc pip install python-pptx ``` 然后,可以使用以下代码将Markdown文件转换为PPT文件: ```python import subprocess import os from pptx import Presentation def convert_to_ppt(md_file, ppt_file): # Convert markdown to docx docx_file = md_file.split('.')[0] + '.docx' cmd = ['pandoc', md_file, '-o', docx_file] subprocess.call(cmd) # Convert docx to pptx prs = Presentation() slide_layout = prs.slide_layouts[1] cmd = ['libreoffice', '--headless', '--convert-to', 'pptx', docx_file, '--outdir', os.getcwd()] subprocess.call(cmd) pptx_file = docx_file.split('.')[0] + '.pptx' # Insert slides into pptx slides = Presentation(pptx_file).slides for slide in slides: prs_slide = prs.slides.add_slide(slide_layout) for shape in slide.shapes: el = shape.element newel = el.clone() prs_slide.shapes._spTree.insert_element_before(newel, 'p:extLst') # Save pptx file prs.save(ppt_file) # Remove temporary files os.remove(docx_file) os.remove(pptx_file) # Example usage convert_to_ppt('example.md', 'example.pptx') ``` 这段代码将Markdown文件转换docx文件,再将docx文件转换为pptx文件,最后将pptx文件中的所有幻灯片插入到新创建的PPT文件中,并保存为指定的文件名。注意,这里使用了LibreOffice来进行docx和pptx文件转换,因此需要在系统中安装LibreOffice并将其添加到系统路径中。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Lion King

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

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

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

打赏作者

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

抵扣说明:

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

余额充值