推荐6款Python文本格式处理库

发表时间: 2018-02-22 09:56

以下是一些 Python 编写的用来解析和操作特殊文本格式的库,希望对大家有所帮助。

1、Tablib

Tablib 是一个用来处理与表格格式数据有关的 Python 库,允许导入、导出、管理表格格式数据,并具备包括切片、动态列、标签和过滤,以及格式化导入和导出等高级功能。

Tablib 支持导出/导入的格式包括:Excel 、JSON 、YAML 、HTML 、TSV 和 CSV ,暂不支持 XML 。

>>> data = tablib.Dataset(headers=['First Name', 'Last Name', 'Age'])>>> for i in [('Kenneth', 'Reitz', 22), ('Bessie', 'Monke', 21)]:... data.append(i)>>> print(data.export('json'))[{"Last Name": "Reitz", "First Name": "Kenneth", "Age": 22}, {"Last Name": "Monke", "First Name": "Bessie", "Age": 21}]>>> print(data.export('yaml'))- {Age: 22, First Name: Kenneth, Last Name: Reitz}- {Age: 21, First Name: Bessie, Last Name: Monke}>>> data.export('xlsx')<censored binary data>>>> data.export('df') First Name Last Name Age0 Kenneth Reitz 221 Bessie Monke 21

2、Openpyxl

Openpyxl 是一个用于读写 Excel 2010 xlsx / xlsm / xltx / xltm 文件的 Python 库。

Openpyxl 为 Python 原生读取/写入 Office Open XML 格式而生,最初是基于 PHPExcel 而开发。

from openpyxl import Workbookwb = Workbook()# grab the active worksheetws = wb.active# Data can be assigned directly to cellsws['A1'] = 42# Rows can also be appendedws.append([1, 2, 3])# Python types will automatically be convertedimport datetimews['A2'] = datetime.datetime.now()# Save the filewb.save("sample.xlsx")

3、unoconv

unoconv,全称为 Universal Office Converter ,是一个命令行工具,可在 LibreOffice/OpenOffice 支持的任意文件格式之间进行转换。

unoconv 支持批量转换文档,还可以结合 asciidoc和 docbook2odf / xhtml2odt 来创建 PDF 或 Word(.doc) 文件。

[dag@moria cv]$ make odt pdf html docrm -f *.{odt,pdf,html,doc}asciidoc -b docbook -d article -o resume.xml resume.txtdocbook2odf -f --params generate.meta=0 -o resume.tmp.odt resume.xmlSaved resume.tmp.odtunoconv -f odt -t template.ott -o resume.odt resume.tmp.odtunoconv -f pdf -t template.ott -o resume.pdf resume.odtunoconv -f html -t template.ott -o resume.html resume.odtunoconv -f doc -t template.ott -o resume.doc resume.odt

4、PyPDF2

PyPDF2 是一个纯 Python PDF 库,能够分割、合并、裁剪和转换 PDF 文件页面。它还可以添加自定义数据、查看选项和密码到 PDF 文件。

PyPDF2 可以从 PDF 中检索文本和元数据,也可以将整个文件合并在一起。

from PyPDF2 import PdfFileWriter, PdfFileReaderoutput = PdfFileWriter()input1 = PdfFileReader(open("document1.pdf", "rb"))# print how many pages input1 has:print "document1.pdf has %d pages." % input1.getNumPages()# add page 1 from input1 to output document, unchangedoutput.addPage(input1.getPage(0))# add page 2 from input1, but rotated clockwise 90 degreesoutput.addPage(input1.getPage(1).rotateClockwise(90))# add page 3 from input1, rotated the other way:output.addPage(input1.getPage(2).rotateCounterClockwise(90))# alt: output.addPage(input1.getPage(2).rotateClockwise(270))# add page 4 from input1, but first add a watermark from another PDF:page4 = input1.getPage(3)watermark = PdfFileReader(open("watermark.pdf", "rb"))page4.mergePage(watermark.getPage(0))output.addPage(page4)# add page 5 from input1, but crop it to half size:page5 = input1.getPage(4)page5.mediaBox.upperRight = ( page5.mediaBox.getUpperRight_x() / 2, page5.mediaBox.getUpperRight_y() / 2)output.addPage(page5)# add some Javascript to launch the print window on opening this PDF.# the password dialog may prevent the print dialog from being shown,# comment the the encription lines, if that's the case, to try this outoutput.addJS("this.print({bUI:true,bSilent:false,bShrinkToFit:true});")# encrypt your new PDF and add a passwordpassword = "secret"output.encrypt(password)# finally, write "output" to document-output.pdfoutputStream = file("PyPDF2-output.pdf", "wb")output.write(outputStream)

5、Mistune

Mistune 是一个纯 Python 实现的 Markdown 解析器,功能齐全,包括表格、注释、代码块等。

Mistune 据称是所有纯 Python markdown 解析器中速度最快的(基准测试结果)。它在设计时考虑了模块化,以提供一个清晰易用的可扩展的 API 。

import mistunemistune.markdown('I am using **mistune markdown parser**')# output: <p>I am using <strong>mistune markdown parser</strong></p>

6、csvkit

csvkit 号称是处理 csv 文件的瑞士军刀,集成了 csvlookcsvcutcsvsql 等实用工具,可以以表格形式显示 CSV 文件,轻松选取 CSV 指定列,以及在其上执行 SQL 操作。

csvkit 是一个命令行工具,灵感来自 pdftk 、gdal 和其它类似工具。