Preface
1. Use tabulate Beautify table output
2. Use prettytable Beautify the output
summary
PrefaceIn use python Processing table data , The focus of this work is to sort out the data of table type 、 Calculate and show , This article focuses on the work of this aspect .
First, let's look at a case , Define an array of table data :
[[email protected] table]$ ipythonPython 3.8.5 (default, Sep 4 2020, 07:30:14) Type 'copyright', 'credits' or 'license' for more informationIPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.In [1]: table=[('a',1,2,3),('b',2,3,4)]In [2]: print(table)[('a', 1, 2, 3), ('b', 2, 3, 4)]
When we print the table data directly , I found the effect very ugly . Although we can get the same information from this form , But this method of data display is very disadvantageous for us to get data directly from the printout .
1. Use tabulate Beautify table outputLet's start with a tool tabulate, You can print table data in array format directly , And there are many output formats to choose from . The installation method can also be used pip To manage :
[[email protected] table]$ python3 -m pip install tabulateRequirement already satisfied: tabulate in /home/dechin/anaconda3/lib/python3.8/site-packages (0.8.9)
It's easy to install , And there's no other dependency .
Next we use ipython To show some basic usage :
[[email protected] table]$ ipythonPython 3.8.5 (default, Sep 4 2020, 07:30:14) Type 'copyright', 'credits' or 'license' for more informationIPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.In [1]: from tabulate import tabulateIn [2]: import numpy as npIn [3]: header=['index']+list(range(4)) # Definition of header In [4]: headerOut[4]: ['index', 0, 1, 2, 3]In [8]: table=[('Alice',1,2,3,4),('Bob',2,3,4,5)] # Definition of table content In [9]: tableOut[9]: [('Alice', 1, 2, 3, 4), ('Bob', 2, 3, 4, 5)]In [11]: print(tabulate(table,headers=header,tablefmt='grid')) # use grid Print the contents of the form in the format of +---------+-----+-----+-----+-----+| index | 0 | 1 | 2 | 3 |+=========+=====+=====+=====+=====+| Alice | 1 | 2 | 3 | 4 |+---------+-----+-----+-----+-----+| Bob | 2 | 3 | 4 | 5 |+---------+-----+-----+-----+-----+In [12]: print(tabulate(table,headers=header,tablefmt='fancy_grid')) # use fancy_grid Format printing ╒═════════╤═════╤═════╤═════╤═════╕│ index │ 0 │ 1 │ 2 │ 3 │╞═════════╪═════╪═════╪═════╪═════╡│ Alice │ 1 │ 2 │ 3 │ 4 │├─────────┼─────┼─────┼─────┼─────┤│ Bob │ 2 │ 3 │ 4 │ 5 │╘═════════╧═════╧═════╧═════╧═════╛
In this case , We have generated the header and table contents of array format respectively , And then use tabulate It's packaged and printed out . because tabulate Supports multiple formats of output , What we're showing here is just grid and fancy_grid Two personal favorite formats
Other types of formats are :
"plain""simple""github""grid""fancy_grid""pipe""orgtbl""jira""presto""psql""rst""mediawiki""moinmoin""youtrack""html""latex""latex_raw""latex_booktabs""textile"
2. Use prettytable Beautify the output Be similar to tabulate Of ,prettytable The main purpose of is also to beautify the output of table data , But there is a slight difference in the way it is used , Different solutions can be used in different scenarios .
So let's take a look here prettytable Installation , It can also be used pip To manage :
[[email protected] table]$ python3 -m pip install prettytableCollecting prettytable Downloading prettytable-2.1.0-py3-none-any.whl (22 kB)Requirement already satisfied: wcwidth in /home/dechin/anaconda3/lib/python3.8/site-packages (from prettytable) (0.2.5)Installing collected packages: prettytableSuccessfully installed prettytable-2.1.0
After the installation, we use a py File to show its usage :
from prettytable import PrettyTabletb = PrettyTable() # Generate table objects tb.field_names = ['Index', 0, 1, 2, 3] # Define header tb.add_row(['Alice',1,2,3,4]) # Add a row , The column is columntb.add_row(['Bob',2,3,4,5])print (tb) # Printout
The code execution results are as follows :
[[email protected] table]$ python3 pt_test.py +-------+---+---+---+---+| Index | 0 | 1 | 2 | 3 |+-------+---+---+---+---+| Alice | 1 | 2 | 3 | 4 || Bob | 2 | 3 | 4 | 5 |+-------+---+---+---+---+
Because the use of the case with the above tabulate It's the same , So the output is similar , Equivalent to one more output format . But in addition to the output format , We found that prettytable Can be a good use of rows and columns to add the form of table operations , The operation habit is closer to the operation form of database , So for people who use databases a lot ,prettytable It might be a better solution for tabular data output .
summaryThis paper introduces two printing tools for table data :tabulate and prettytable Installation and basic use of . Because the table data itself is not standardized on the output format , As a result, the printed data will appear messy , Not conducive to intuitive reading . So the introduction of these two tools , Enhance the readability of the output results . Both have their own advantages and disadvantages in use ,tabulate Support more forms of table styles , and prettytable Then we use the operation form which is closer to the database , For some users, it has natural ecological advantages .
This is about python This is the end of the article on two tools that can beautify the output results of table data , More about python To beautify the output content of the form, please search the previous articles of the software development network or continue to browse the relevant articles below. I hope you can support the software development network in the future !