写在前面:
对于python程序员来说,文件格式之间转换很常用,尤其是把我们爬虫爬到的内容转换成想要的文档格式时。这几天看到一个网站上有许多文章,个人很喜欢,直接复制太麻烦,为了将爬到的html文件以word .doc 文件的格式存储到自己的数据库,选用了pypandoc库。
这个库语法简单,瞄一眼就能会,就跟我一起来看看吧。
安装安装一般先装pandoc 然后安装pypandoc库
1.window
1>安装pandoc:直接下载windows版本的.msi文件即可,传送门 https://github.com/jgm/pandoc/releases/
2>安装pypandoc库:命令行安装,或者直接idea安装
pip install pypandoc
2.ubuntu
sudo apt install pandoc pip install pypandoc
pypandoc主要有3个函数:
1.convert() 2.convent_file() 3.convenr_text()
其中convert()官方建议不用,容易产生歧义。
convert_file()和convent_text()区别就在于一个接收文件参数,一个接收文本参数。结合下面例子一看即懂:
import pypandoc # 将当前目录下html目录中的1.html网页文件直接转换成.docx文件,文件名为file1.docx,并保存在当前目录下的doc文件夹中 pypandoc.convert_file('./html/1.html', 'docx', outputfile="./doc/file1.docx") # # 将当前目录下html目录中的1.html网页文件 读取出来,然后转换成.docx文件,文件名为file2.docx,并保存在当前目录下的doc文件夹中 with open('./html/1.html', encoding='utf-8') as f: f_text = f.read() pypandoc.convert_text(f_text, 'docx', 'html', outputfile="./doc/file2.docx")
一图知晓: