tabulate-0.7.7/ 0000777 0000000 0000000 00000000000 13010122452 011446 5 ustar 0000000 0000000 tabulate-0.7.7/LICENSE 0000666 0000000 0000000 00000002073 12674206067 012501 0 ustar 0000000 0000000 Copyright (c) 2011-2016 Sergey Astanin
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
tabulate-0.7.7/MANIFEST.in 0000666 0000000 0000000 00000000065 12674206067 013231 0 ustar 0000000 0000000 include LICENSE
include README
include README.rst
tabulate-0.7.7/PKG-INFO 0000666 0000000 0000000 00000056652 13010122452 012561 0 ustar 0000000 0000000 Metadata-Version: 1.1
Name: tabulate
Version: 0.7.7
Summary: Pretty-print tabular data
Home-page: https://bitbucket.org/astanin/python-tabulate
Author: Sergey Astanin
Author-email: s.astanin@gmail.com
License: Copyright (c) 2011-2016 Sergey Astanin
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Description: ===============
python-tabulate
===============
Pretty-print tabular data in Python, a library and a command-line
utility.
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: multiple
output formats suitable for further editing or transformation
* readable presentation of mixed textual and numeric data: smart
column alignment, configurable number formatting, alignment by a
decimal point
Installation
------------
To install the Python library and the command line utility, run::
pip install tabulate
The command line utility will be installed as ``tabulate`` to ``bin`` on Linux
(e.g. ``/usr/bin``); or as ``tabulate.exe`` to ``Scripts`` in your Python
installation on Windows (e.g. ``C:\Python27\Scripts\tabulate.exe``).
You may consider installing the library only for the current user::
pip install tabulate --user
In this case the command line utility will be installed to ``~/.local/bin/tabulate``
on Linux and to ``%APPDATA%\Python\Scripts\tabulate.exe`` on Windows.
To install just the library on Unix-like operating systems::
TABULATE_INSTALL=lib-only pip install tabulate
On Windows::
set TABULATE_INSTALL=lib-only
pip install tabulate
Library usage
-------------
The module provides just one function, ``tabulate``, which takes a
list 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
* list or another iterable of dicts (keys as columns)
* dict of iterables (keys as columns)
* two-dimensional NumPy array
* NumPy record arrays (names as columns)
* pandas.DataFrame
Examples in this file use Python2. Tabulate supports Python3 too.
Headers
~~~~~~~
The second optional argument named ``headers`` defines a list of
column 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. It also works for NumPy record arrays and
lists of dictionaries or named tuples::
>>> print tabulate({"Name": ["Alice", "Bob"],
... "Age": [24, 19]}, headers="keys")
Age Name
----- ------
24 Alice
19 Bob
Row Indices
~~~~~~~~~~~
By default, only pandas.DataFrame tables have an additional column
called row index. To add a similar column to any other type of table,
pass ``showindex="always"`` or ``showindex=True`` argument to
``tabulate()``. To suppress row indices for all types of data, pass
``showindex="never"`` or ``showindex=False``. To add a custom row
index column, pass ``showindex=rowIDs``, where ``rowIDs`` is some
iterable::
>>> print(tabulate([["F",24],["M",19]], showindex="always"))
- - --
0 F 24
1 M 19
- - --
Table format
~~~~~~~~~~~~
There is more than one way to format a table in plain text.
The third optional argument named ``tablefmt`` defines
how the table is formatted.
Supported table formats are:
- "plain"
- "simple"
- "grid"
- "fancy_grid"
- "pipe"
- "orgtbl"
- "jira"
- "psql"
- "rst"
- "mediawiki"
- "moinmoin"
- "html"
- "latex"
- "latex_booktabs"
- "textile"
``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 future
versions). It corresponds to ``simple_tables`` in `Pandoc Markdown
extensions`::
>>> print tabulate(table, headers, tablefmt="simple")
item qty
------ -----
spam 42
eggs 451
bacon 0
``grid`` is like tables formatted by Emacs' `table.el`
package. It corresponds to ``grid_tables`` in Pandoc Markdown
extensions::
>>> print tabulate(table, headers, tablefmt="grid")
+--------+-------+
| item | qty |
+========+=======+
| spam | 42 |
+--------+-------+
| eggs | 451 |
+--------+-------+
| bacon | 0 |
+--------+-------+
``fancy_grid`` draws a grid using box-drawing characters::
>>> print tabulate(table, headers, tablefmt="fancy_grid")
╒════════╤═══════╕
│ item │ qty │
╞════════╪═══════╡
│ spam │ 42 │
├────────┼───────┤
│ eggs │ 451 │
├────────┼───────┤
│ bacon │ 0 │
╘════════╧═══════╛
``psql`` is like tables formatted by Postgres' psql cli::
>>> print tabulate.tabulate()
+--------+-------+
| item | qty |
|--------+-------|
| spam | 42 |
| eggs | 451 |
| bacon | 0 |
+--------+-------+
``pipe`` follows the conventions of `PHP Markdown Extra` extension. It
corresponds to ``pipe_tables`` in Pandoc. This format uses colons to
indicate 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 editable
also in the minor `orgtbl-mode`. Hence its name::
>>> print tabulate(table, headers, tablefmt="orgtbl")
| item | qty |
|--------+-------|
| spam | 42 |
| eggs | 451 |
| bacon | 0 |
``jira`` follows the conventions of Atlassian Jira markup language::
>>> print tabulate(table, headers, tablefmt="jira")
|| 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 in `Wikipedia` and on
other MediaWiki-based sites::
>>> print tabulate(table, headers, tablefmt="mediawiki")
{| class="wikitable" style="text-align: left;"
|+
|-
! item !! align="right"| qty
|-
| spam || align="right"| 42
|-
| eggs || align="right"| 451
|-
| bacon || align="right"| 0
|}
``moinmoin`` format produces a table markup used in `MoinMoin`
wikis::
>>> print tabulate(d,headers,tablefmt="moinmoin")
|| ''' item ''' || ''' quantity ''' ||
|| spam || 41.999 ||
|| eggs || 451 ||
|| bacon || ||
``textile`` format produces a table markup used in `Textile` format::
>>> print tabulate(table, headers, tablefmt='textile')
|_. item |_. qty |
|<. spam |>. 42 |
|<. eggs |>. 451 |
|<. bacon |>. 0 |
``html`` produces standard HTML markup::
>>> print tabulate(table, headers, tablefmt="html")
item | qty |
spam | 42 |
eggs | 451 |
bacon | 0 |
``latex`` format creates a ``tabular`` environment for LaTeX markup::
>>> print tabulate(table, headers, tablefmt="latex")
\begin{tabular}{lr}
\hline
item & qty \\
\hline
spam & 42 \\
eggs & 451 \\
bacon & 0 \\
\hline
\end{tabular}
``latex_booktabs`` creates a ``tabular`` environment for LaTeX markup
using spacing and style from the ``booktabs`` package.
.. _Pandoc Markdown extensions: http://johnmacfarlane.net/pandoc/README.html#tables
.. _PHP Markdown Extra: http://michelf.ca/projects/php-markdown/extra/#table
.. _table.el: http://table.sourceforge.net/
.. _org-mode: http://orgmode.org/manual/Tables.html
.. _reStructuredText: http://docutils.sourceforge.net/docs/user/rst/quickref.html#tables
.. _Textile: http://redcloth.org/hobix.com/textile/
.. _Wikipedia: http://www.mediawiki.org/wiki/Help:Tables
Column alignment
~~~~~~~~~~~~~~~~
``tabulate`` is smart about column alignment. It detects columns which
contain only numbers, and aligns them by a decimal point (or flushes
them to the right if they appear to be integers). Text columns are
flushed to the left.
You can override the default alignment with ``numalign`` and
``stralign`` named arguments. Possible column alignments are:
``right``, ``center``, ``left``, ``decimal`` (only for numbers), and
``None`` (to disable alignment).
Aligning by a decimal point works best when you need to compare
numbers 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 a
number. Even numbers represented as strings are aligned properly. This
feature comes in handy when reading a mixed table of text and numbers
from 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 all
columns of decimal numbers. Use ``floatfmt`` named argument::
>>> print tabulate([["pi",3.141593],["e",2.718282]], floatfmt=".4f")
-- ------
pi 3.1416
e 2.7183
-- ------
Wide (fullwidth CJK) symbols
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To properly align tables which contain wide characters (typically fullwidth
glyphs from Chinese, Japanese or Korean languages), the user should install
``wcwidth`` library. To install it together with ``tabulate``::
pip install tabulate[widechars]
Wide character support is enabled automatically if ``wcwidth`` library is
already installed. To disable wide characters support without uninstalling
``wcwidth``, set the global module-level flag ``WIDE_CHARS_MODE``::
import tabulate
tabulate.WIDE_CHARS_MODE = False
Usage of the command line utility
---------------------------------
::
Usage: tabulate [options] [FILE ...]
FILE a filename of the file with tabular data;
if "-" or missing, read data from stdin.
Options:
-h, --help show this message
-1, --header use the first row of data as a table header
-o FILE, --output FILE print table to FILE (default: stdout)
-s REGEXP, --sep REGEXP use a custom column separator (default: whitespace)
-F FPFMT, --float FPFMT floating point number format (default: g)
-f FMT, --format FMT set output table format; supported formats:
plain, simple, grid, fancy_grid, pipe, orgtbl,
rst, mediawiki, html, latex, latex_booktabs, tsv
(default: simple)
Performance considerations
--------------------------
Such features as decimal point alignment and trying to parse everything
as a number imply that ``tabulate``:
* 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's
going to do that, anyway?) or printing tables in performance sensitive
applications. ``tabulate`` is about two orders of magnitude slower
than simply joining lists of values with a tab, coma or other
separator.
In the same time ``tabulate`` is comparable to other table
pretty-printers. Given a 10x10 table (a list of lists) of mixed text
and numeric data, ``tabulate`` appears to be slower than
``asciitable``, and faster than ``PrettyTable`` and ``texttable``
::
================================= ========== ===========
Table formatter time, μs rel. time
================================= ========== ===========
csv to StringIO 25.3 1.0
join with tabs and newlines 33.6 1.3
asciitable (0.8.0) 590.0 23.4
tabulate (0.7.7) 1403.5 55.6
tabulate (0.7.7, WIDE_CHARS_MODE) 2156.6 85.4
PrettyTable (0.7.2) 3377.0 133.7
texttable (0.8.6) 3986.3 157.8
================================= ========== ===========
Version history
---------------
- 0.8: FUTURE RELEASE
- 0.7.6: Bug fixes. New table formats (``psql``, ``jira``, ``moinmoin``, ``textile``).
Wide character support. Printing from database cursors.
Option to print row indices. Boolean columns. Ragged rows.
Option to disable number parsing.
- 0.7.5: Bug fixes. ``--float`` format option for the command line utility.
- 0.7.4: Bug fixes. ``fancy_grid`` and ``html`` formats. Command line utility.
- 0.7.3: Bug fixes. Python 3.4 support. Iterables of dicts. ``latex_booktabs`` format.
- 0.7.2: Python 3.2 support.
- 0.7.1: Bug fixes. ``tsv`` format. Column alignment can be disabled.
- 0.7: ``latex`` tables. Printing lists of named tuples and NumPy
record arrays. Fix printing date and time values. Python <= 2.6.4 is supported.
- 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``.
How to contribute
-----------------
Contributions should include tests and an explanation for the changes they
propose. Documentation (examples, docstrings, README.rst) should be updated
accordingly.
This project uses `nose` testing framework and `tox` to automate testing in
different environments. Add tests to one of the files in the ``test/`` folder.
To run tests on all supported Python versions, make sure all Python
interpreters, ``nose`` and ``tox`` are installed, then run ``tox`` in
the root of the project source tree.
On Linux ``tox`` expects to find executables like ``python2.6``,
``python2.7``, ``python3.4`` etc. On Windows it looks for
``C:\Python26\python.exe``, ``C:\Python27\python.exe`` and
``C:\Python34\python.exe`` respectively.
To test only some Python environements, use ``-e`` option. For
example, to test only against Python 2.7 and Python 3.4, run::
tox -e py27,py34
in the root of the project source tree.
To enable NumPy and Pandas tests, run::
tox -e py27-extra,py34-extra
(this may take a long time the first time, because NumPy and Pandas
will have to be installed in the new virtual environments)
See ``tox.ini`` file to learn how to use ``nosetests`` directly to
test individual Python versions.
.. _nose: https://nose.readthedocs.org/
.. _tox: http://tox.testrun.org/
Contributors
------------
Sergey Astanin, Pau Tallada Crespí, Erwin Marsi, Mik Kocikowski, Bill Ryder,
Zach Dwiel, Frederik Rietdijk, Philipp Bogensberger, Greg (anonymous),
Stefan Tatschner, Emiel van Miltenburg, Brandon Bennett, Amjith Ramanujam,
Jan Schulz, Simon Percivall, Javier Santacruz López-Cepero, Sam Denton,
Alexey Ziyangirov, acaird, Cesar Sanchez, naught101, John Vandenberg,
Zack Dever.
Platform: UNKNOWN
Classifier: Development Status :: 4 - Beta
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3.2
Classifier: Programming Language :: Python :: 3.3
Classifier: Programming Language :: Python :: 3.4
Classifier: Topic :: Software Development :: Libraries
tabulate-0.7.7/README 0000666 0000000 0000000 00000000014 12674206067 012345 0 ustar 0000000 0000000 ./README.rst tabulate-0.7.7/README.rst 0000666 0000000 0000000 00000043117 13010122216 013141 0 ustar 0000000 0000000 ===============
python-tabulate
===============
Pretty-print tabular data in Python, a library and a command-line
utility.
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: multiple
output formats suitable for further editing or transformation
* readable presentation of mixed textual and numeric data: smart
column alignment, configurable number formatting, alignment by a
decimal point
Installation
------------
To install the Python library and the command line utility, run::
pip install tabulate
The command line utility will be installed as ``tabulate`` to ``bin`` on Linux
(e.g. ``/usr/bin``); or as ``tabulate.exe`` to ``Scripts`` in your Python
installation on Windows (e.g. ``C:\Python27\Scripts\tabulate.exe``).
You may consider installing the library only for the current user::
pip install tabulate --user
In this case the command line utility will be installed to ``~/.local/bin/tabulate``
on Linux and to ``%APPDATA%\Python\Scripts\tabulate.exe`` on Windows.
To install just the library on Unix-like operating systems::
TABULATE_INSTALL=lib-only pip install tabulate
On Windows::
set TABULATE_INSTALL=lib-only
pip install tabulate
Build status
------------
.. image:: https://drone.io/bitbucket.org/astanin/python-tabulate/status.png
:alt: Build status
:target: https://drone.io/bitbucket.org/astanin/python-tabulate/latest
Library usage
-------------
The module provides just one function, ``tabulate``, which takes a
list 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
* list or another iterable of dicts (keys as columns)
* dict of iterables (keys as columns)
* two-dimensional NumPy array
* NumPy record arrays (names as columns)
* pandas.DataFrame
Examples in this file use Python2. Tabulate supports Python3 too.
Headers
~~~~~~~
The second optional argument named ``headers`` defines a list of
column 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. It also works for NumPy record arrays and
lists of dictionaries or named tuples::
>>> print tabulate({"Name": ["Alice", "Bob"],
... "Age": [24, 19]}, headers="keys")
Age Name
----- ------
24 Alice
19 Bob
Row Indices
~~~~~~~~~~~
By default, only pandas.DataFrame tables have an additional column
called row index. To add a similar column to any other type of table,
pass ``showindex="always"`` or ``showindex=True`` argument to
``tabulate()``. To suppress row indices for all types of data, pass
``showindex="never"`` or ``showindex=False``. To add a custom row
index column, pass ``showindex=rowIDs``, where ``rowIDs`` is some
iterable::
>>> print(tabulate([["F",24],["M",19]], showindex="always"))
- - --
0 F 24
1 M 19
- - --
Table format
~~~~~~~~~~~~
There is more than one way to format a table in plain text.
The third optional argument named ``tablefmt`` defines
how the table is formatted.
Supported table formats are:
- "plain"
- "simple"
- "grid"
- "fancy_grid"
- "pipe"
- "orgtbl"
- "jira"
- "psql"
- "rst"
- "mediawiki"
- "moinmoin"
- "html"
- "latex"
- "latex_booktabs"
- "textile"
``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 future
versions). It corresponds to ``simple_tables`` in `Pandoc Markdown
extensions`_::
>>> print tabulate(table, headers, tablefmt="simple")
item qty
------ -----
spam 42
eggs 451
bacon 0
``grid`` is like tables formatted by Emacs' `table.el`_
package. It corresponds to ``grid_tables`` in Pandoc Markdown
extensions::
>>> print tabulate(table, headers, tablefmt="grid")
+--------+-------+
| item | qty |
+========+=======+
| spam | 42 |
+--------+-------+
| eggs | 451 |
+--------+-------+
| bacon | 0 |
+--------+-------+
``fancy_grid`` draws a grid using box-drawing characters::
>>> print tabulate(table, headers, tablefmt="fancy_grid")
╒════════╤═══════╕
│ item │ qty │
╞════════╪═══════╡
│ spam │ 42 │
├────────┼───────┤
│ eggs │ 451 │
├────────┼───────┤
│ bacon │ 0 │
╘════════╧═══════╛
``psql`` is like tables formatted by Postgres' psql cli::
>>> print tabulate.tabulate()
+--------+-------+
| item | qty |
|--------+-------|
| spam | 42 |
| eggs | 451 |
| bacon | 0 |
+--------+-------+
``pipe`` follows the conventions of `PHP Markdown Extra`_ extension. It
corresponds to ``pipe_tables`` in Pandoc. This format uses colons to
indicate 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 editable
also in the minor `orgtbl-mode`. Hence its name::
>>> print tabulate(table, headers, tablefmt="orgtbl")
| item | qty |
|--------+-------|
| spam | 42 |
| eggs | 451 |
| bacon | 0 |
``jira`` follows the conventions of Atlassian Jira markup language::
>>> print tabulate(table, headers, tablefmt="jira")
|| 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 in `Wikipedia`_ and on
other MediaWiki-based sites::
>>> print tabulate(table, headers, tablefmt="mediawiki")
{| class="wikitable" style="text-align: left;"
|+
|-
! item !! align="right"| qty
|-
| spam || align="right"| 42
|-
| eggs || align="right"| 451
|-
| bacon || align="right"| 0
|}
``moinmoin`` format produces a table markup used in `MoinMoin`_
wikis::
>>> print tabulate(d,headers,tablefmt="moinmoin")
|| ''' item ''' || ''' quantity ''' ||
|| spam || 41.999 ||
|| eggs || 451 ||
|| bacon || ||
``textile`` format produces a table markup used in `Textile`_ format::
>>> print tabulate(table, headers, tablefmt='textile')
|_. item |_. qty |
|<. spam |>. 42 |
|<. eggs |>. 451 |
|<. bacon |>. 0 |
``html`` produces standard HTML markup::
>>> print tabulate(table, headers, tablefmt="html")
item | qty |
spam | 42 |
eggs | 451 |
bacon | 0 |
``latex`` format creates a ``tabular`` environment for LaTeX markup::
>>> print tabulate(table, headers, tablefmt="latex")
\begin{tabular}{lr}
\hline
item & qty \\
\hline
spam & 42 \\
eggs & 451 \\
bacon & 0 \\
\hline
\end{tabular}
``latex_booktabs`` creates a ``tabular`` environment for LaTeX markup
using spacing and style from the ``booktabs`` package.
.. _Pandoc Markdown extensions: http://johnmacfarlane.net/pandoc/README.html#tables
.. _PHP Markdown Extra: http://michelf.ca/projects/php-markdown/extra/#table
.. _table.el: http://table.sourceforge.net/
.. _org-mode: http://orgmode.org/manual/Tables.html
.. _reStructuredText: http://docutils.sourceforge.net/docs/user/rst/quickref.html#tables
.. _Textile: http://redcloth.org/hobix.com/textile/
.. _Wikipedia: http://www.mediawiki.org/wiki/Help:Tables
Column alignment
~~~~~~~~~~~~~~~~
``tabulate`` is smart about column alignment. It detects columns which
contain only numbers, and aligns them by a decimal point (or flushes
them to the right if they appear to be integers). Text columns are
flushed to the left.
You can override the default alignment with ``numalign`` and
``stralign`` named arguments. Possible column alignments are:
``right``, ``center``, ``left``, ``decimal`` (only for numbers), and
``None`` (to disable alignment).
Aligning by a decimal point works best when you need to compare
numbers 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 a
number. Even numbers represented as strings are aligned properly. This
feature comes in handy when reading a mixed table of text and numbers
from 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 all
columns of decimal numbers. Use ``floatfmt`` named argument::
>>> print tabulate([["pi",3.141593],["e",2.718282]], floatfmt=".4f")
-- ------
pi 3.1416
e 2.7183
-- ------
Wide (fullwidth CJK) symbols
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To properly align tables which contain wide characters (typically fullwidth
glyphs from Chinese, Japanese or Korean languages), the user should install
``wcwidth`` library. To install it together with ``tabulate``::
pip install tabulate[widechars]
Wide character support is enabled automatically if ``wcwidth`` library is
already installed. To disable wide characters support without uninstalling
``wcwidth``, set the global module-level flag ``WIDE_CHARS_MODE``::
import tabulate
tabulate.WIDE_CHARS_MODE = False
Usage of the command line utility
---------------------------------
::
Usage: tabulate [options] [FILE ...]
FILE a filename of the file with tabular data;
if "-" or missing, read data from stdin.
Options:
-h, --help show this message
-1, --header use the first row of data as a table header
-o FILE, --output FILE print table to FILE (default: stdout)
-s REGEXP, --sep REGEXP use a custom column separator (default: whitespace)
-F FPFMT, --float FPFMT floating point number format (default: g)
-f FMT, --format FMT set output table format; supported formats:
plain, simple, grid, fancy_grid, pipe, orgtbl,
rst, mediawiki, html, latex, latex_booktabs, tsv
(default: simple)
Performance considerations
--------------------------
Such features as decimal point alignment and trying to parse everything
as a number imply that ``tabulate``:
* 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's
going to do that, anyway?) or printing tables in performance sensitive
applications. ``tabulate`` is about two orders of magnitude slower
than simply joining lists of values with a tab, coma or other
separator.
In the same time ``tabulate`` is comparable to other table
pretty-printers. Given a 10x10 table (a list of lists) of mixed text
and numeric data, ``tabulate`` appears to be slower than
``asciitable``, and faster than ``PrettyTable`` and ``texttable``
::
================================= ========== ===========
Table formatter time, μs rel. time
================================= ========== ===========
csv to StringIO 25.3 1.0
join with tabs and newlines 33.6 1.3
asciitable (0.8.0) 590.0 23.4
tabulate (0.7.7) 1403.5 55.6
tabulate (0.7.7, WIDE_CHARS_MODE) 2156.6 85.4
PrettyTable (0.7.2) 3377.0 133.7
texttable (0.8.6) 3986.3 157.8
================================= ========== ===========
Version history
---------------
- 0.8: FUTURE RELEASE
- 0.7.6: Bug fixes. New table formats (``psql``, ``jira``, ``moinmoin``, ``textile``).
Wide character support. Printing from database cursors.
Option to print row indices. Boolean columns. Ragged rows.
Option to disable number parsing.
- 0.7.5: Bug fixes. ``--float`` format option for the command line utility.
- 0.7.4: Bug fixes. ``fancy_grid`` and ``html`` formats. Command line utility.
- 0.7.3: Bug fixes. Python 3.4 support. Iterables of dicts. ``latex_booktabs`` format.
- 0.7.2: Python 3.2 support.
- 0.7.1: Bug fixes. ``tsv`` format. Column alignment can be disabled.
- 0.7: ``latex`` tables. Printing lists of named tuples and NumPy
record arrays. Fix printing date and time values. Python <= 2.6.4 is supported.
- 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``.
How to contribute
-----------------
Contributions should include tests and an explanation for the changes they
propose. Documentation (examples, docstrings, README.rst) should be updated
accordingly.
This project uses `nose`_ testing framework and `tox`_ to automate testing in
different environments. Add tests to one of the files in the ``test/`` folder.
To run tests on all supported Python versions, make sure all Python
interpreters, ``nose`` and ``tox`` are installed, then run ``tox`` in
the root of the project source tree.
On Linux ``tox`` expects to find executables like ``python2.6``,
``python2.7``, ``python3.4`` etc. On Windows it looks for
``C:\Python26\python.exe``, ``C:\Python27\python.exe`` and
``C:\Python34\python.exe`` respectively.
To test only some Python environements, use ``-e`` option. For
example, to test only against Python 2.7 and Python 3.4, run::
tox -e py27,py34
in the root of the project source tree.
To enable NumPy and Pandas tests, run::
tox -e py27-extra,py34-extra
(this may take a long time the first time, because NumPy and Pandas
will have to be installed in the new virtual environments)
See ``tox.ini`` file to learn how to use ``nosetests`` directly to
test individual Python versions.
.. _nose: https://nose.readthedocs.org/
.. _tox: http://tox.testrun.org/
Contributors
------------
Sergey Astanin, Pau Tallada Crespí, Erwin Marsi, Mik Kocikowski, Bill Ryder,
Zach Dwiel, Frederik Rietdijk, Philipp Bogensberger, Greg (anonymous),
Stefan Tatschner, Emiel van Miltenburg, Brandon Bennett, Amjith Ramanujam,
Jan Schulz, Simon Percivall, Javier Santacruz López-Cepero, Sam Denton,
Alexey Ziyangirov, acaird, Cesar Sanchez, naught101, John Vandenberg,
Zack Dever.
tabulate-0.7.7/setup.cfg 0000666 0000000 0000000 00000000100 13010122452 013256 0 ustar 0000000 0000000 [egg_info]
tag_build =
tag_date = 0
tag_svn_revision = 0
tabulate-0.7.7/setup.py 0000666 0000000 0000000 00000004322 13010122163 013160 0 ustar 0000000 0000000 #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from platform import python_version_tuple, python_implementation
import os
import re
LICENSE = open("LICENSE").read()
# strip links from the descripton on the PyPI
if python_version_tuple()[0] >= '3':
LONG_DESCRIPTION = open("README.rst", "r", encoding="utf-8").read().replace("`_", "`")
else:
LONG_DESCRIPTION = open("README.rst", "r").read().replace("`_", "`")
# strip Build Status from the PyPI package
try:
if python_version_tuple()[:2] >= ('2', '7'):
status_re = "^Build status\n(.*\n){7}"
LONG_DESCRIPTION = re.sub(status_re, "", LONG_DESCRIPTION, flags=re.M)
except TypeError:
if python_implementation() == "IronPython":
# IronPython doesn't support flags in re.sub (IronPython issue #923)
pass
else:
raise
install_options = os.environ.get("TABULATE_INSTALL","").split(",")
libonly_flags = set(["lib-only", "libonly", "no-cli", "without-cli"])
if libonly_flags.intersection(install_options):
console_scripts = []
else:
console_scripts = ['tabulate = tabulate:_main']
setup(name='tabulate',
version='0.7.7',
description='Pretty-print tabular data',
long_description=LONG_DESCRIPTION,
author='Sergey Astanin',
author_email='s.astanin@gmail.com',
url='https://bitbucket.org/astanin/python-tabulate',
license=LICENSE,
classifiers= [ "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.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: Software Development :: Libraries" ],
py_modules = ['tabulate'],
entry_points = {'console_scripts': console_scripts},
extras_require = {'widechars': ['wcwidth']},
test_suite = 'nose.collector')
tabulate-0.7.7/tabulate.egg-info/ 0000777 0000000 0000000 00000000000 13010122452 014741 5 ustar 0000000 0000000 tabulate-0.7.7/tabulate.egg-info/.PKG-INFO.swp 0000666 0000000 0000000 00000040000 13010120704 016714 0 ustar 0000000 0000000 b0VIM 7.4 g X sergey ROCCANERA C:/Users/sergey/Checkout/python-tabulate/tabulate.egg-info/PKG-INFO 3210#"! U tp ] k ^ d _ - [ K 2 ad ] p Y 7 <
o
U
T
Q G
f
U
L
D _ G > 5 . : 1 U L r Q H ? )
u ; 2 o I Mars 3390 641.85 Moon 1737 73.5 Earth 6371 5973.6 Sun 696000 1.9891e+09 ----- ------ ------------- >>> print tabulate(table) ... ["Moon",1737,73.5],["Mars",3390,641.85]] >>> table = [["Sun",696000,1989100000],["Earth",6371,5973.6], >>> from tabulate import tabulate and outputs a nicely formatted plain-text table:: list of lists or another tabular data type as the first argument, The module provides just one function, ``tabulate``, which takes a ------------- Library usage pip install tabulate set TABULATE_INSTALL=lib-only On Windows:: TABULATE_INSTALL=lib-only pip install tabulate To install just the library on Unix-like operating systems:: on Linux and to ``%APPDATA%\Python\Scripts\tabulate.exe`` on Windows. In this case the command line utility will be installed to ``~/.local/bin/tabulate`` pip install tabulate --user You may consider installing the library only for the current user:: installation on Windows (e.g. ``C:\Python27\Scripts\tabulate.exe``). (e.g. ``/usr/bin``); or as ``tabulate.exe`` to ``Scripts`` in your Python The command line utility will be installed as ``tabulate`` to ``bin`` on Linux pip install tabulate To install the Python library and the command line utility, run:: ------------ Installation decimal point column alignment, configurable number formatting, alignment by a * readable presentation of mixed textual and numeric data: smart output formats suitable for further editing or transformation * authoring tabular data for lightweight plain-text markup: multiple formatting is guided by the data itself * printing small tables without hassle: just one function call, The main use cases of the library are: utility. Pretty-print tabular data in Python, a library and a command-line =============== python-tabulate Description: =============== WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, included in all copies or substantial portions of the Software. The above copyright notice and this permission notice shall be the following conditions: permit persons to whom the Software is furnished to do so, subject to distribute, sublicense, and/or sell copies of the Software, and to without limitation the rights to use, copy, modify, merge, publish, "Software"), to deal in the Software without restriction, including a copy of this software and associated documentation files (the Permission is hereby granted, free of charge, to any person obtaining License: Copyright (c) 2011-2016 Sergey Astanin Author-email: s.astanin@gmail.com Author: Sergey Astanin Home-page: https://bitbucket.org/astanin/python-tabulate Summary: Pretty-print tabular data Version: 0.7.6 Name: tabulate Metadata-Version: 1.1 ad
i @ 7 C
P
u F ~ L Classifier: Topic :: Software Development :: Libraries Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 2.6 Classifier: Operating System :: OS Independent Classifier: License :: OSI Approved :: MIT License Classifier: Development Status :: 4 - Beta Platform: UNKNOWN Zack Dever. Alexey Ziyangirov, acaird, Cesar Sanchez, naught101, John Vandenberg, Jan Schulz, Simon Percivall, Javier Santacruz López-Cepero, Sam Denton, Stefan Tatschner, Emiel van Miltenburg, Brandon Bennett, Amjith Ramanujam, Zach Dwiel, Frederik Rietdijk, Philipp Bogensberger, Greg (anonymous), Sergey Astanin, Pau Tallada Crespí, Erwin Marsi, Mik Kocikowski, Bill Ryder, ------------ Contributors .. _tox: http://tox.testrun.org/ .. _nose: https://nose.readthedocs.org/ test individual Python versions. See ``tox.ini`` file to learn how to use ``nosetests`` directly to will have to be installed in the new virtual environments) tabulate-0.7.7/tabulate.egg-info/dependency_links.txt 0000666 0000000 0000000 00000000001 13010122452 021007 0 ustar 0000000 0000000
tabulate-0.7.7/tabulate.egg-info/entry_points.txt 0000666 0000000 0000000 00000000055 13010122452 020237 0 ustar 0000000 0000000 [console_scripts]
tabulate = tabulate:_main
tabulate-0.7.7/tabulate.egg-info/PKG-INFO 0000666 0000000 0000000 00000056652 13010122452 016054 0 ustar 0000000 0000000 Metadata-Version: 1.1
Name: tabulate
Version: 0.7.7
Summary: Pretty-print tabular data
Home-page: https://bitbucket.org/astanin/python-tabulate
Author: Sergey Astanin
Author-email: s.astanin@gmail.com
License: Copyright (c) 2011-2016 Sergey Astanin
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Description: ===============
python-tabulate
===============
Pretty-print tabular data in Python, a library and a command-line
utility.
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: multiple
output formats suitable for further editing or transformation
* readable presentation of mixed textual and numeric data: smart
column alignment, configurable number formatting, alignment by a
decimal point
Installation
------------
To install the Python library and the command line utility, run::
pip install tabulate
The command line utility will be installed as ``tabulate`` to ``bin`` on Linux
(e.g. ``/usr/bin``); or as ``tabulate.exe`` to ``Scripts`` in your Python
installation on Windows (e.g. ``C:\Python27\Scripts\tabulate.exe``).
You may consider installing the library only for the current user::
pip install tabulate --user
In this case the command line utility will be installed to ``~/.local/bin/tabulate``
on Linux and to ``%APPDATA%\Python\Scripts\tabulate.exe`` on Windows.
To install just the library on Unix-like operating systems::
TABULATE_INSTALL=lib-only pip install tabulate
On Windows::
set TABULATE_INSTALL=lib-only
pip install tabulate
Library usage
-------------
The module provides just one function, ``tabulate``, which takes a
list 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
* list or another iterable of dicts (keys as columns)
* dict of iterables (keys as columns)
* two-dimensional NumPy array
* NumPy record arrays (names as columns)
* pandas.DataFrame
Examples in this file use Python2. Tabulate supports Python3 too.
Headers
~~~~~~~
The second optional argument named ``headers`` defines a list of
column 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. It also works for NumPy record arrays and
lists of dictionaries or named tuples::
>>> print tabulate({"Name": ["Alice", "Bob"],
... "Age": [24, 19]}, headers="keys")
Age Name
----- ------
24 Alice
19 Bob
Row Indices
~~~~~~~~~~~
By default, only pandas.DataFrame tables have an additional column
called row index. To add a similar column to any other type of table,
pass ``showindex="always"`` or ``showindex=True`` argument to
``tabulate()``. To suppress row indices for all types of data, pass
``showindex="never"`` or ``showindex=False``. To add a custom row
index column, pass ``showindex=rowIDs``, where ``rowIDs`` is some
iterable::
>>> print(tabulate([["F",24],["M",19]], showindex="always"))
- - --
0 F 24
1 M 19
- - --
Table format
~~~~~~~~~~~~
There is more than one way to format a table in plain text.
The third optional argument named ``tablefmt`` defines
how the table is formatted.
Supported table formats are:
- "plain"
- "simple"
- "grid"
- "fancy_grid"
- "pipe"
- "orgtbl"
- "jira"
- "psql"
- "rst"
- "mediawiki"
- "moinmoin"
- "html"
- "latex"
- "latex_booktabs"
- "textile"
``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 future
versions). It corresponds to ``simple_tables`` in `Pandoc Markdown
extensions`::
>>> print tabulate(table, headers, tablefmt="simple")
item qty
------ -----
spam 42
eggs 451
bacon 0
``grid`` is like tables formatted by Emacs' `table.el`
package. It corresponds to ``grid_tables`` in Pandoc Markdown
extensions::
>>> print tabulate(table, headers, tablefmt="grid")
+--------+-------+
| item | qty |
+========+=======+
| spam | 42 |
+--------+-------+
| eggs | 451 |
+--------+-------+
| bacon | 0 |
+--------+-------+
``fancy_grid`` draws a grid using box-drawing characters::
>>> print tabulate(table, headers, tablefmt="fancy_grid")
╒════════╤═══════╕
│ item │ qty │
╞════════╪═══════╡
│ spam │ 42 │
├────────┼───────┤
│ eggs │ 451 │
├────────┼───────┤
│ bacon │ 0 │
╘════════╧═══════╛
``psql`` is like tables formatted by Postgres' psql cli::
>>> print tabulate.tabulate()
+--------+-------+
| item | qty |
|--------+-------|
| spam | 42 |
| eggs | 451 |
| bacon | 0 |
+--------+-------+
``pipe`` follows the conventions of `PHP Markdown Extra` extension. It
corresponds to ``pipe_tables`` in Pandoc. This format uses colons to
indicate 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 editable
also in the minor `orgtbl-mode`. Hence its name::
>>> print tabulate(table, headers, tablefmt="orgtbl")
| item | qty |
|--------+-------|
| spam | 42 |
| eggs | 451 |
| bacon | 0 |
``jira`` follows the conventions of Atlassian Jira markup language::
>>> print tabulate(table, headers, tablefmt="jira")
|| 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 in `Wikipedia` and on
other MediaWiki-based sites::
>>> print tabulate(table, headers, tablefmt="mediawiki")
{| class="wikitable" style="text-align: left;"
|+
|-
! item !! align="right"| qty
|-
| spam || align="right"| 42
|-
| eggs || align="right"| 451
|-
| bacon || align="right"| 0
|}
``moinmoin`` format produces a table markup used in `MoinMoin`
wikis::
>>> print tabulate(d,headers,tablefmt="moinmoin")
|| ''' item ''' || ''' quantity ''' ||
|| spam || 41.999 ||
|| eggs || 451 ||
|| bacon || ||
``textile`` format produces a table markup used in `Textile` format::
>>> print tabulate(table, headers, tablefmt='textile')
|_. item |_. qty |
|<. spam |>. 42 |
|<. eggs |>. 451 |
|<. bacon |>. 0 |
``html`` produces standard HTML markup::
>>> print tabulate(table, headers, tablefmt="html")
item | qty |
spam | 42 |
eggs | 451 |
bacon | 0 |
``latex`` format creates a ``tabular`` environment for LaTeX markup::
>>> print tabulate(table, headers, tablefmt="latex")
\begin{tabular}{lr}
\hline
item & qty \\
\hline
spam & 42 \\
eggs & 451 \\
bacon & 0 \\
\hline
\end{tabular}
``latex_booktabs`` creates a ``tabular`` environment for LaTeX markup
using spacing and style from the ``booktabs`` package.
.. _Pandoc Markdown extensions: http://johnmacfarlane.net/pandoc/README.html#tables
.. _PHP Markdown Extra: http://michelf.ca/projects/php-markdown/extra/#table
.. _table.el: http://table.sourceforge.net/
.. _org-mode: http://orgmode.org/manual/Tables.html
.. _reStructuredText: http://docutils.sourceforge.net/docs/user/rst/quickref.html#tables
.. _Textile: http://redcloth.org/hobix.com/textile/
.. _Wikipedia: http://www.mediawiki.org/wiki/Help:Tables
Column alignment
~~~~~~~~~~~~~~~~
``tabulate`` is smart about column alignment. It detects columns which
contain only numbers, and aligns them by a decimal point (or flushes
them to the right if they appear to be integers). Text columns are
flushed to the left.
You can override the default alignment with ``numalign`` and
``stralign`` named arguments. Possible column alignments are:
``right``, ``center``, ``left``, ``decimal`` (only for numbers), and
``None`` (to disable alignment).
Aligning by a decimal point works best when you need to compare
numbers 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 a
number. Even numbers represented as strings are aligned properly. This
feature comes in handy when reading a mixed table of text and numbers
from 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 all
columns of decimal numbers. Use ``floatfmt`` named argument::
>>> print tabulate([["pi",3.141593],["e",2.718282]], floatfmt=".4f")
-- ------
pi 3.1416
e 2.7183
-- ------
Wide (fullwidth CJK) symbols
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To properly align tables which contain wide characters (typically fullwidth
glyphs from Chinese, Japanese or Korean languages), the user should install
``wcwidth`` library. To install it together with ``tabulate``::
pip install tabulate[widechars]
Wide character support is enabled automatically if ``wcwidth`` library is
already installed. To disable wide characters support without uninstalling
``wcwidth``, set the global module-level flag ``WIDE_CHARS_MODE``::
import tabulate
tabulate.WIDE_CHARS_MODE = False
Usage of the command line utility
---------------------------------
::
Usage: tabulate [options] [FILE ...]
FILE a filename of the file with tabular data;
if "-" or missing, read data from stdin.
Options:
-h, --help show this message
-1, --header use the first row of data as a table header
-o FILE, --output FILE print table to FILE (default: stdout)
-s REGEXP, --sep REGEXP use a custom column separator (default: whitespace)
-F FPFMT, --float FPFMT floating point number format (default: g)
-f FMT, --format FMT set output table format; supported formats:
plain, simple, grid, fancy_grid, pipe, orgtbl,
rst, mediawiki, html, latex, latex_booktabs, tsv
(default: simple)
Performance considerations
--------------------------
Such features as decimal point alignment and trying to parse everything
as a number imply that ``tabulate``:
* 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's
going to do that, anyway?) or printing tables in performance sensitive
applications. ``tabulate`` is about two orders of magnitude slower
than simply joining lists of values with a tab, coma or other
separator.
In the same time ``tabulate`` is comparable to other table
pretty-printers. Given a 10x10 table (a list of lists) of mixed text
and numeric data, ``tabulate`` appears to be slower than
``asciitable``, and faster than ``PrettyTable`` and ``texttable``
::
================================= ========== ===========
Table formatter time, μs rel. time
================================= ========== ===========
csv to StringIO 25.3 1.0
join with tabs and newlines 33.6 1.3
asciitable (0.8.0) 590.0 23.4
tabulate (0.7.7) 1403.5 55.6
tabulate (0.7.7, WIDE_CHARS_MODE) 2156.6 85.4
PrettyTable (0.7.2) 3377.0 133.7
texttable (0.8.6) 3986.3 157.8
================================= ========== ===========
Version history
---------------
- 0.8: FUTURE RELEASE
- 0.7.6: Bug fixes. New table formats (``psql``, ``jira``, ``moinmoin``, ``textile``).
Wide character support. Printing from database cursors.
Option to print row indices. Boolean columns. Ragged rows.
Option to disable number parsing.
- 0.7.5: Bug fixes. ``--float`` format option for the command line utility.
- 0.7.4: Bug fixes. ``fancy_grid`` and ``html`` formats. Command line utility.
- 0.7.3: Bug fixes. Python 3.4 support. Iterables of dicts. ``latex_booktabs`` format.
- 0.7.2: Python 3.2 support.
- 0.7.1: Bug fixes. ``tsv`` format. Column alignment can be disabled.
- 0.7: ``latex`` tables. Printing lists of named tuples and NumPy
record arrays. Fix printing date and time values. Python <= 2.6.4 is supported.
- 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``.
How to contribute
-----------------
Contributions should include tests and an explanation for the changes they
propose. Documentation (examples, docstrings, README.rst) should be updated
accordingly.
This project uses `nose` testing framework and `tox` to automate testing in
different environments. Add tests to one of the files in the ``test/`` folder.
To run tests on all supported Python versions, make sure all Python
interpreters, ``nose`` and ``tox`` are installed, then run ``tox`` in
the root of the project source tree.
On Linux ``tox`` expects to find executables like ``python2.6``,
``python2.7``, ``python3.4`` etc. On Windows it looks for
``C:\Python26\python.exe``, ``C:\Python27\python.exe`` and
``C:\Python34\python.exe`` respectively.
To test only some Python environements, use ``-e`` option. For
example, to test only against Python 2.7 and Python 3.4, run::
tox -e py27,py34
in the root of the project source tree.
To enable NumPy and Pandas tests, run::
tox -e py27-extra,py34-extra
(this may take a long time the first time, because NumPy and Pandas
will have to be installed in the new virtual environments)
See ``tox.ini`` file to learn how to use ``nosetests`` directly to
test individual Python versions.
.. _nose: https://nose.readthedocs.org/
.. _tox: http://tox.testrun.org/
Contributors
------------
Sergey Astanin, Pau Tallada Crespí, Erwin Marsi, Mik Kocikowski, Bill Ryder,
Zach Dwiel, Frederik Rietdijk, Philipp Bogensberger, Greg (anonymous),
Stefan Tatschner, Emiel van Miltenburg, Brandon Bennett, Amjith Ramanujam,
Jan Schulz, Simon Percivall, Javier Santacruz López-Cepero, Sam Denton,
Alexey Ziyangirov, acaird, Cesar Sanchez, naught101, John Vandenberg,
Zack Dever.
Platform: UNKNOWN
Classifier: Development Status :: 4 - Beta
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3.2
Classifier: Programming Language :: Python :: 3.3
Classifier: Programming Language :: Python :: 3.4
Classifier: Topic :: Software Development :: Libraries
tabulate-0.7.7/tabulate.egg-info/requires.txt 0000666 0000000 0000000 00000000025 13010122452 017336 0 ustar 0000000 0000000
[widechars]
wcwidth
tabulate-0.7.7/tabulate.egg-info/SOURCES.txt 0000666 0000000 0000000 00000000575 13010122452 016634 0 ustar 0000000 0000000 LICENSE
MANIFEST.in
README
README.rst
setup.py
tabulate.py
tabulate.egg-info/.PKG-INFO.swp
tabulate.egg-info/PKG-INFO
tabulate.egg-info/SOURCES.txt
tabulate.egg-info/dependency_links.txt
tabulate.egg-info/entry_points.txt
tabulate.egg-info/requires.txt
tabulate.egg-info/top_level.txt
test/test_api.py
test/test_cli.py
test/test_input.py
test/test_output.py
test/test_regression.py tabulate-0.7.7/tabulate.egg-info/top_level.txt 0000666 0000000 0000000 00000000011 13010122452 017463 0 ustar 0000000 0000000 tabulate
tabulate-0.7.7/tabulate.py 0000666 0000000 0000000 00000142023 13010122175 013625 0 ustar 0000000 0000000 # -*- coding: utf-8 -*-
"""Pretty-print tabular data."""
from __future__ import print_function
from __future__ import unicode_literals
from collections import namedtuple, Iterable
from platform import python_version_tuple
import re
if python_version_tuple()[0] < "3":
from itertools import izip_longest
from functools import partial
_none_type = type(None)
_bool_type = bool
_int_type = int
_long_type = long
_float_type = float
_text_type = unicode
_binary_type = str
def _is_file(f):
return isinstance(f, file)
else:
from itertools import zip_longest as izip_longest
from functools import reduce, partial
_none_type = type(None)
_bool_type = bool
_int_type = int
_long_type = int
_float_type = float
_text_type = str
_binary_type = bytes
import io
def _is_file(f):
return isinstance(f, io.IOBase)
try:
import wcwidth # optional wide-character (CJK) support
except ImportError:
wcwidth = None
__all__ = ["tabulate", "tabulate_formats", "simple_separated_format"]
__version__ = "0.7.7"
# minimum extra space in headers
MIN_PADDING = 2
# if True, enable wide-character (CJK) support
WIDE_CHARS_MODE = wcwidth is not None
Line = namedtuple("Line", ["begin", "hline", "sep", "end"])
DataRow = namedtuple("DataRow", ["begin", "sep", "end"])
# A table structure is suppposed to be:
#
# --- lineabove ---------
# headerrow
# --- linebelowheader ---
# datarow
# --- linebewteenrows ---
# ... (more datarows) ...
# --- linebewteenrows ---
# last datarow
# --- linebelow ---------
#
# TableFormat's line* elements can be
#
# - either None, if the element is not used,
# - or a Line tuple,
# - or a function: [col_widths], [col_alignments] -> string.
#
# TableFormat's *row elements can be
#
# - either None, if the element is not used,
# - or a DataRow tuple,
# - or a function: [cell_values], [col_widths], [col_alignments] -> string.
#
# padding (an integer) is the amount of white space around data values.
#
# with_header_hide:
#
# - either None, to display all table elements unconditionally,
# - or a list of elements not to be displayed if the table has column headers.
#
TableFormat = namedtuple("TableFormat", ["lineabove", "linebelowheader",
"linebetweenrows", "linebelow",
"headerrow", "datarow",
"padding", "with_header_hide"])
def _pipe_segment_with_colons(align, colwidth):
"""Return a segment of a horizontal line with optional colons which
indicate column's alignment (as in `pipe` output format)."""
w = colwidth
if align in ["right", "decimal"]:
return ('-' * (w - 1)) + ":"
elif align == "center":
return ":" + ('-' * (w - 2)) + ":"
elif align == "left":
return ":" + ('-' * (w - 1))
else:
return '-' * w
def _pipe_line_with_colons(colwidths, colaligns):
"""Return a horizontal line with optional colons to indicate column's
alignment (as in `pipe` output format)."""
segments = [_pipe_segment_with_colons(a, w) for a, w in zip(colaligns, colwidths)]
return "|" + "|".join(segments) + "|"
def _mediawiki_row_with_attrs(separator, cell_values, colwidths, colaligns):
alignment = { "left": '',
"right": 'align="right"| ',
"center": 'align="center"| ',
"decimal": 'align="right"| ' }
# hard-coded padding _around_ align attribute and value together
# rather than padding parameter which affects only the value
values_with_attrs = [' ' + alignment.get(a, '') + c + ' '
for c, a in zip(cell_values, colaligns)]
colsep = separator*2
return (separator + colsep.join(values_with_attrs)).rstrip()
def _textile_row_with_attrs(cell_values, colwidths, colaligns):
cell_values[0] += ' '
alignment = { "left": "<.", "right": ">.", "center": "=.", "decimal": ">." }
values = (alignment.get(a, '') + v for a, v in zip(colaligns, cell_values))
return '|' + '|'.join(values) + '|'
def _html_begin_table_without_header(colwidths_ignore, colaligns_ignore):
# this table header will be suppressed if there is a header row
return "\n".join(["", ""])
def _html_row_with_attrs(celltag, cell_values, colwidths, colaligns):
alignment = { "left": '',
"right": ' style="text-align: right;"',
"center": ' style="text-align: center;"',
"decimal": ' style="text-align: right;"' }
values_with_attrs = ["<{0}{1}>{2}{0}>".format(celltag, alignment.get(a, ''), c)
for c, a in zip(cell_values, colaligns)]
rowhtml = "" + "".join(values_with_attrs).rstrip() + "
"
if celltag == "th": # it's a header row, create a new table header
rowhtml = "\n".join(["",
"",
rowhtml,
"",
""])
return rowhtml
def _moin_row_with_attrs(celltag, cell_values, colwidths, colaligns, header=''):
alignment = { "left": '',
"right": '