专栏首页python3python 打印表单格式

python 打印表单格式

https://pypi.python.org/pypi/tabulate

对于老版本的python可能有兼容问题

Some places still have legacy environments that are slowly migrating to newer versions. I was able to resolve it by just removing the unicode_literals and utf. Thanks for the response!

https://bitbucket.org/astanin/python-tabulate/issue/4/__new__-keywords-must-be-strings-in-linux

这样改过之后直接用其文件而不用库,就可以解决问题。

tabulate 0.6

Download tabulate-0.6.tar.gz

Pretty-print tabular data

Pretty-print tabular data in Python.

The main use cases of the library are:

  • printing small tables without hassle: just one function call,formatting is guided by the data itself
  • authoring tabular data for lightweight plain-text markup: multipleoutput formats suitable for further editing or transformation
  • readable presentation of mixed textual and numeric data: smartcolumn alignment, configurable number formatting, alignment by adecimal point

Installation

pip install tabulate

Usage

The module provides just one function, tabulate, which takes alist of lists or another tabular data type as the first argument,and outputs a nicely formatted plain-text table:

>>> from tabulate import tabulate

>>> table = [["Sun",696000,1989100000],["Earth",6371,5973.6],
...          ["Moon",1737,73.5],["Mars",3390,641.85]]
>>> print tabulate(table)
-----  ------  -------------
Sun    696000     1.9891e+09
Earth    6371  5973.6
Moon     1737    73.5
Mars     3390   641.85
-----  ------  -------------

The following tabular data types are supported:

  • list of lists or another iterable of iterables
  • dict of iterables
  • two-dimensional NumPy array
  • pandas.DataFrame

Examples in this file use Python2. Tabulate supports Python3 too (Python >= 3.3).

Headers

The second optional argument named headers defines a list ofcolumn headers to be used:

>>> print tabulate(table, headers=["Planet","R (km)", "mass (x 10^29 kg)"])
Planet      R (km)    mass (x 10^29 kg)
--------  --------  -------------------
Sun         696000           1.9891e+09
Earth         6371        5973.6
Moon          1737          73.5
Mars          3390         641.85

If headers="firstrow", then the first row of data is used:

>>> print tabulate([["Name","Age"],["Alice",24],["Bob",19]],
...                headers="firstrow")
Name      Age
------  -----
Alice      24
Bob        19

If headers="keys", then the keys of a dictionary/dataframe,or column indices are used:

>>> print tabulate({"Name": ["Alice", "Bob"],
...                 "Age": [24, 19]}, headers="keys")
  Age  Name
-----  ------
   24  Alice
   19  Bob

Table format

There is more than one way to format a table in plain text.The third optional argument namedtablefmt defineshow the table is formatted.

Supported table formats are:

  • "plain"
  • "simple"
  • "grid"
  • "pipe"
  • "orgtbl"
  • "rst"
  • "mediawiki"

plain tables do not use any pseudo-graphics to draw lines:

>>> table = [["spam",42],["eggs",451],["bacon",0]]
>>> headers = ["item", "qty"]
>>> print tabulate(table, headers, tablefmt="plain")
item      qty
spam       42
eggs      451
bacon       0

simple is the default format (the default may change in futureversions). It corresponds tosimple_tables in Pandoc Markdownextensions:

>>> print tabulate(table, headers, tablefmt="simple")
item      qty
------  -----
spam       42
eggs      451
bacon       0

grid is like tables formatted by Emacs' table.elpackage. It corresponds to grid_tables in Pandoc Markdownextensions:

>>> print tabulate(table, headers, tablefmt="grid")
+--------+-------+
| item   |   qty |
+========+=======+
| spam   |    42 |
+--------+-------+
| eggs   |   451 |
+--------+-------+
| bacon  |     0 |
+--------+-------+

pipe follows the conventions of PHP Markdown Extra extension. Itcorresponds topipe_tables in Pandoc. This format uses colons toindicate column alignment:

>>> print tabulate(table, headers, tablefmt="pipe")
| item   |   qty |
|:-------|------:|
| spam   |    42 |
| eggs   |   451 |
| bacon  |     0 |

orgtbl follows the conventions of Emacs org-mode, and is editablealso in the minor orgtbl-mode. Hence its name:

>>> print tabulate(table, headers, tablefmt="orgtbl")
| item   |   qty |
|--------+-------|
| spam   |    42 |
| eggs   |   451 |
| bacon  |     0 |

rst formats data like a simple table of the reStructuredText format:

>>> print tabulate(table, headers, tablefmt="rst")
======  =====
item      qty
======  =====
spam       42
eggs      451
bacon       0
======  =====

mediawiki format produces a table markup used inWikipedia and onother MediaWiki-based sites:

>>> print tabulate(table, headers, tablefmt="mediawiki")
{| class="wikitable" style="text-align: left;"
|+ <!-- caption -->
|-
! item   !! align="right"|   qty
|-
| spam   || align="right"|    42
|-
| eggs   || align="right"|   451
|-
| bacon  || align="right"|     0
|}

Column alignment

tabulate is smart about column alignment. It detects columns whichcontain only numbers, and aligns them by a decimal point (or flushesthem to the right if they appear to be integers). Text columns areflushed to the left.

You can override the default alignment with numalign andstralign named arguments. Possible column alignments are:right,center,left, decimal (only for numbers).

Aligning by a decimal point works best when you need to comparenumbers at a glance:

>>> print tabulate([[1.2345],[123.45],[12.345],[12345],[1234.5]])
----------
    1.2345
  123.45
   12.345
12345
 1234.5
----------

Compare this with a more common right alignment:

>>> print tabulate([[1.2345],[123.45],[12.345],[12345],[1234.5]], numalign="right")
------
1.2345
123.45
12.345
 12345
1234.5
------

For tabulate, anything which can be parsed as a number is anumber. Even numbers represented as strings are aligned properly. Thisfeature comes in handy when reading a mixed table of text and numbersfrom a file:

>>> import csv ; from StringIO import StringIO
>>> table = list(csv.reader(StringIO("spam, 42\neggs, 451\n")))
>>> table
[['spam', ' 42'], ['eggs', ' 451']]
>>> print tabulate(table)
----  ----
spam    42
eggs   451
----  ----

Number formatting

tabulate allows to define custom number formatting applied to allcolumns of decimal numbers. Usefloatfmt named argument:

>>> print tabulate([["pi",3.141593],["e",2.718282]], floatfmt=".4f")
--  ------
pi  3.1416
e   2.7183
--  ------

Performance considerations

Such features as decimal point alignment and trying to parse everythingas a number imply thattabulate:

  • has to "guess" how to print a particular tabular data type
  • needs to keep the entire table in-memory
  • has to "transpose" the table twice
  • does much more work than it may appear

It may not be suitable for serializing really big tables (but who'sgoing to do that, anyway?) or printing tables in performance sensitiveapplications.tabulate is about two orders of magnitude slowerthan simply joining lists of values with a tab, coma or otherseparator.

In the same time tabulate is comparable to other tablepretty-printers. Given a 10x10 table (a list of lists) of mixed textand numeric data,tabulate appears to be slower thanasciitable, and faster thanPrettyTable and texttable

===========================  ==========  ===========
Table formatter                time, μs    rel. time
===========================  ==========  ===========
join with tabs and newlines        34.7          1.0
csv to StringIO                    49.1          1.4
asciitable (0.8.0)               1272.1         36.7
tabulate (0.6)                   1964.5         56.6
PrettyTable (0.7.1)              5678.9        163.7
texttable (0.8.1)                6005.2        173.1
===========================  ==========  ===========

Version history

  • 0.6: mediawiki tables, bug fixes
  • 0.5.1: Fix README.rst formatting. Optimize (performance similar to 0.4.4).
  • 0.5: ANSI color sequences. Printing dicts of iterables and Pandas' dataframes.
  • 0.4.4: Python 2.6 support
  • 0.4.3: Bug fix, None as a missing value
  • 0.4.2: Fix manifest file
  • 0.4.1: Update license and documentation.
  • 0.4: Unicode support, Python3 support, rst tables
  • 0.3: Initial PyPI release. Table formats: simple,plain,grid, pipe, and orgtbl.

File

Type

Py Version

Uploaded on

Size

tabulate-0.6.tar.gz (md5)

Source

2013-08-09

14KB

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 系统运维工程师的法宝:python pa

    安装:pip install Paramiko paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连...

    py3study
  • 一个python版的开源web截图工具:

    http://github.com/AdamN/python-webkit2png/ 一个使用pyqt4里的QtWebkit实现的命令行的web截图软件,可用...

    py3study
  • 用Python实现语音播报

    以下内容为带着儿子一起学Python的实现记录,为自己保存下来,也希望对其他学习者有用!

    py3study
  • 分发战略对分布式账本安全的影响(CS DC)

    本文对基于分布式账本技术的安全攻击进行了仿真研究。我们特别关注这些系统的底层对等层的攻击,该层负责传播包含将在所有参与者之间传播的数据和事务的消息。特别地,我们...

    邱邱邱
  • 学习从图像推断用户界面属性(cs CV)

    我们探索了一个学习推断用户界面属性的新领域,这将有助于开发人员自动执行用户界面实现过程。更具体来说,给定一个设计师创建的输入图像,我们学习推断它的实现,当渲染时...

    DANDAN用户6837186
  • 如何制作一个自动驾驶小车(含代码)

    I’ve just finished a recent side project with my friend Kendrick. (his GitHub) ...

    用户1908973
  • iOS苹果审核2.1解决方案审核机制

    近几个月来,在苹果审核中,只要应用中涉及,支付,定位等涉及用户隐私的功能,苹果都会部分青红皂白的打回来,这其实很可能不是APP本身的原因,只是苹果要你自查。

    Lee坚武
  • I Gave Up Instagram and 30,000 Followers

    平时有很多碎片化时间,比如下班的地铁上,或者等待的时间,我们总喜欢拿出手机玩,这个时间也可以用来学习呢,当然佳爷自己也想学习英语,所以上下班的时间看看。

    仇诺伊
  • Copying Books POJ - 1505 二分答案 详细注释

    种花家的奋斗兔
  • codeforce1196C

    n robots have escaped from your laboratory! You have to find them as soon as pos...

    dejavu1zz

扫码关注云+社区

领取腾讯云代金券