python 打印表单格式

2023-01-31 02:01:01 格式 表单 打印
对于老版本的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
这样改过之后直接用其文件而不用库,就可以解决问题。

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
pip install tabulate

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
--  ------

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
===========================  ==========  ===========
  • 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
 
  • Downloads (All Versions):
  • 45 downloads in the last day
  • 223 downloads in the last week
  • 676 downloads in the last month
  • Author: Sergey Astanin
  • Categories
    • Development Status :: 4 - Beta
    • License :: OSI Approved :: MIT License
    • Operating System :: OS Independent
    • Programming Language :: Python :: 2.6
    • Programming Language :: Python :: 2.7
    • Programming Language :: Python :: 3.3
    • Topic :: Software Development :: Libraries

相关文章