跳转至

PrettyTable 教程

原文: http://zetcode.com/python/prettytable/

PrettyTable 教程展示了如何使用 Python PrettyTable 模块在 Python 中生成 ASCII 表。 在本教程中,我们使用PTable模块,该模块是原始 PrettyTable 库的分支。

PrettyTable

PrettyTable 是用于生成简单 ASCII 表的 Python 库。 它的灵感来自 PostgreSQL shell psql中使用的 ASCII 表。 我们可以控制表格的许多方面,例如列填充的宽度,文本的对齐方式或表格边框。 我们可以对数据进行排序。

我们还可以选择在最终输出中将显示哪些列和行。 PrettyTable 可以从 CSV,HTML 或数据库游标读取数据,并以 ASCII 或 HTML 输出数据。

PrettyTable 安装

$ sudo pip3 install PTable

我们使用pip3工具安装 PrettyTable。

生成 PrettyTable

可以使用add_row()add_column()方法创建表。

create_by_row.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable()

x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]

x.add_row(["Adelaide", 1295, 1158259, 600.5])
x.add_row(["Brisbane", 5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print(x)

该示例使用add_row()方法创建一个 PrettyTable。

from prettytable import PrettyTable

从模块中,我们导入PrettyTable

x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]

我们设置标题名称。

x.add_row(["Adelaide", 1295, 1158259, 600.5])
x.add_row(["Brisbane", 5905, 1857594, 1146.4])

这些行通过add_row()添加到表中。

print(x)

最后,我们将表格打印到控制台。

$ ./create_by_row.py 
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
|  Adelaide | 1295 |  1158259   |      600.5      |
|  Brisbane | 5905 |  1857594   |      1146.4     |
|   Darwin  | 112  |   120900   |      1714.7     |
|   Hobart  | 1357 |   205556   |      619.5      |
|   Sydney  | 2058 |  4336374   |      1214.8     |
| Melbourne | 1566 |  3806092   |      646.9      |
|   Perth   | 5386 |  1554769   |      869.4      |
+-----------+------+------------+-----------------+

这是输出。

在下一个示例中,我们使用add_column()方法创建相同的表。

create_by_column.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable()

column_names = ["City name", "Area", "Population", "Annual Rainfall"]

x.add_column(column_names[0], ["Adelaide", "Brisbane", "Darwin", 
    "Hobart", "Sydney", "Melbourne", "Perth"])
x.add_column(column_names[1], [1295, 5905, 112, 1357, 2058, 1566, 5386 ])  
x.add_column(column_names[2], [1158259, 1857594, 120900, 205556, 4336374, 
    3806092, 1554769])  
x.add_column(column_names[3], [600.5, 1146.4, 1714.7, 619.5, 1214.8, 
    646.9, 869.4])

print(x)

列名是add_column()方法的第一个参数。

PrettyTable 删除行

使用del_row()可以删除特定的行。 该方法获取要删除的行的索引。 请注意,索引从零开始。

delete_rows.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable()

x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]

x.add_row(["Adelaide", 1295, 1158259, 600.5])
x.add_row(["Brisbane", 5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

x.del_row(6)
x.del_row(5)
x.del_row(4)
x.del_row(3)

print(x)

在示例中,我们删除最后四行。

$ ./delete_rows.py 
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
|  Adelaide | 1295 |  1158259   |      600.5      |
|  Brisbane | 5905 |  1857594   |      1146.4     |
|   Darwin  | 112  |   120900   |      1714.7     |
+-----------+------+------------+-----------------+

前三行保留在输出中。

PrettyTable 清除数据

clear_rows()方法从表中删除所有行,但保留当前的列名。 clear()方法清除行名和列名。

clear_rows.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable()

x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]

x.add_row(["Adelaide", 1295, 1158259, 600.5])
x.add_row(["Brisbane", 5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

x.clear_rows()
print(x)

该示例清除表中的所有行。

$ ./clear_rows.py 
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
+-----------+------+------------+-----------------+

这是示例的输出。 该表的标题不会被删除。

从 CSV 生成 PrettyTable

from_csv()方法可用于从 CSV 数据生成 PrettyTable。

data.csv

"City name", "Area", "Population", "Annual Rainfall"
"Adelaide", 1295, 1158259, 600.5
"Brisbane", 5905, 1857594, 1146.4
"Darwin", 112, 120900, 1714.7
"Hobart", 1357, 205556, 619.5
"Sydney", 2058, 4336374, 1214.8
"Melbourne", 1566, 3806092, 646.9
"Perth", 5386, 1554769, 869.4

data.csv包含用逗号分隔的数据。 请注意,第一行由表列名称组成。

read_from_csv.py

#!/usr/bin/python3

from prettytable import from_csv

with open("data.csv", "r") as fp: 
    x = from_csv(fp)

print(x)

该示例从data.csv读取数据,并从中生成带有from_csv()的 PrettyTable。

从数据库游标生成 PrettyTable

from_db_cursor()方法从数据库游标生成 PrettyTable。

cities.sql

DROP TABLE IF EXISTS Cities;

CREATE TABLE Cities(Id INTEGER PRIMARY KEY, Name TEXT, Area INTEGER, 
    Population INTEGER, Rainfall REAL);

INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Adelaide", 1295, 1158259, 600.5);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Brisbane", 5905, 1857594, 1146.4);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Darwin", 112, 120900, 1714.7);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Hobart", 1357, 205556, 619.5);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Sydney", 2058, 4336374, 1214.8);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Melbourne", 1566, 3806092, 646.9);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Perth", 5386, 1554769, 869.4);

这是一个 SQL 脚本,用于在 SQLite 数据库中创建Cities表。

$ sqlite3 data.db 
sqlite> .read cities.sql 
sqlite> SELECT * FROM Cities;
Id          Name        Area        Population  Rainfall  
----------  ----------  ----------  ----------  ----------
1           Adelaide    1295        1158259     600.5     
2           Brisbane    5905        1857594     1146.4    
3           Darwin      112         120900      1714.7    
4           Hobart      1357        205556      619.5     
5           Sydney      2058        4336374     1214.8    
6           Melbourne   1566        3806092     646.9     
7           Perth       5386        1554769     869.4  

我们阅读了cities.sql脚本,该脚本生成数据库表。

read_from_cursor.py

#!/usr/bin/python3

import sqlite3 as lite
from prettytable import from_db_cursor

con = lite.connect('data.db')

with con:

    cur = con.cursor()    
    cur.execute('SELECT * FROM Cities')   

    x = from_db_cursor(cur) 

print(x)

在代码示例中,我们连接到data.db数据库并从Cities表中选择所有数据。 我们使用from_db_cursor()方法从游标生成一个 PrettyTable。

从 HTML 生成 PrettyTable

from_html()从一串 HTML 代码生成一个 PrettyTables 列表。 HTML 中的每个<table>都成为一个 PrettyTable 对象。 from_html_one()从仅包含单个<table>的 HTML 代码字符串中生成 PrettyTable。

data.html

<html>
    <body>
        <table>
            <tr>
                <th>City name</th>
                <th>Area</th>
                <th>Population</th>
                <th>Annual Rainfall</th>
            </tr>
            <tr>
                <td>Adelaide</td>
                <td>1295</td>
                <td>1158259</td>
                <td>600.5</td>
            </tr>
            <tr>
                <td>Brisbane</td>
                <td>5905</td>
                <td>1857594</td>
                <td>1146.4</td>
            </tr>
            <tr>
                <td>Darwin</td>
                <td>112</td>
                <td>120900</td>
                <td>1714.7</td>
            </tr>
            <tr>
                <td>Hobart</td>
                <td>1357</td>
                <td>205556</td>
                <td>619.5</td>
            </tr>
            <tr>
                <td>Sydney</td>
                <td>2058</td>
                <td>4336374</td>
                <td>1214.8</td>
            </tr>
            <tr>
                <td>Melbourne</td>
                <td>1566</td>
                <td>3806092</td>
                <td>646.9</td>
            </tr>
            <tr>
                <td>Perth</td>
                <td>5386</td>
                <td>1554769</td>
                <td>869.4</td>
            </tr>
        </table>
    </body>
</html>

在示例中,我们使用此 HTML 文件。

read_from_html.py

#!/usr/bin/python3

from prettytable import from_html_one

with open("data.html", "r") as fp: 
    html = fp.read()

x = from_html_one(html)
print(x)

该示例从data.html文件中读取数据,并使用from_html_one()方法生成一个 PrettyTable。

排序数据

使用sortby属性,我们将指定要排序的列。 reversesort属性控制排序的方向(升序还是降序)。

sorting.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable()
x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]

x.add_row(["Adelaide", 1295, 1158259, 600.5])
x.add_row(["Brisbane", 5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print("Table sorted by population:")
x.sortby = "Population"
print(x)

print()

print("Table sorted by city in descendig order:")
x.sortby = "City name"
x.reversesort = True
print(x)

在示例中,我们对表的数据进行排序。

print("Table sorted by population:")
x.sortby = "Population"

首先,我们按总体升序对数据进行排序。

x.sortby = "City name"
x.reversesort = True

然后,我们按照城市名称的降序对数据进行排序。

$ ./sorting.py 
Table sorted by population:
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
|   Darwin  | 112  |   120900   |      1714.7     |
|   Hobart  | 1357 |   205556   |      619.5      |
|  Adelaide | 1295 |  1158259   |      600.5      |
|   Perth   | 5386 |  1554769   |      869.4      |
|  Brisbane | 5905 |  1857594   |      1146.4     |
| Melbourne | 1566 |  3806092   |      646.9      |
|   Sydney  | 2058 |  4336374   |      1214.8     |
+-----------+------+------------+-----------------+

Table sorted by city in descendig order:
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
|   Sydney  | 2058 |  4336374   |      1214.8     |
|   Perth   | 5386 |  1554769   |      869.4      |
| Melbourne | 1566 |  3806092   |      646.9      |
|   Hobart  | 1357 |   205556   |      619.5      |
|   Darwin  | 112  |   120900   |      1714.7     |
|  Brisbane | 5905 |  1857594   |      1146.4     |
|  Adelaide | 1295 |  1158259   |      600.5      |
+-----------+------+------------+-----------------+

这是输出。

数据对齐

align属性控制字段的对齐方式。 其可能的值为lcr

alignment.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable()

x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]

x.align["City name"] = "l"
x.align["Area"] = "r"
x.align["Annual Rainfall"] = "r"

x.add_row(["Adelaide", 1295, 1158259, 600.5])
x.add_row(["Brisbane", 5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print(x)

该代码示例在表格列中对齐数据。

x.align["City name"] = "l"

我们将City name列中的字段对齐到左侧。

x.align["Area"] = "r"
x.align["Annual Rainfall"] = "r"

我们将AreaAnnual Rainfall中的字段右对齐。

$ ./alignment.py 
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide  | 1295 |  1158259   |           600.5 |
| Brisbane  | 5905 |  1857594   |          1146.4 |
| Darwin    |  112 |   120900   |          1714.7 |
| Hobart    | 1357 |   205556   |           619.5 |
| Sydney    | 2058 |  4336374   |          1214.8 |
| Melbourne | 1566 |  3806092   |           646.9 |
| Perth     | 5386 |  1554769   |           869.4 |
+-----------+------+------------+-----------------+

这是输出。

HTML 输出

get_html_string()从 PrettyTable 生成 HTML 输出。

html_output.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])

x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print(x.get_html_string())

该示例将 HTML 表中的数据打印到控制台。

get_string方法

get_string()方法返回当前状态下的表的字符串表示形式。 它有几个选项可以控制表格的显示方式。

显示标题

使用title参数,我们可以在输出中包括表标题。

table_title.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])

x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print(x.get_string(title="Australian cities"))

该示例创建一个带标题的 PrettyTable。

$ ./table_title.py 
+-------------------------------------------------+
|                Australian cities                |
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
|  Adelaide | 1295 |  1158259   |      600.5      |
|  Brisbane | 5905 |  1857594   |      1146.4     |
|   Darwin  | 112  |   120900   |      1714.7     |
|   Hobart  | 1357 |   205556   |      619.5      |
|   Sydney  | 2058 |  4336374   |      1214.8     |
| Melbourne | 1566 |  3806092   |      646.9      |
|   Perth   | 5386 |  1554769   |      869.4      |
+-----------+------+------------+-----------------+

这是输出。

选择列

使用fields选项,我们可以选择将要显示的列。

select_columns.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])

x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print(x.get_string(fields=["City name", "Population"]))

在该示例中,我们仅显示City namePopulation列。

$ ./select_columns.py 
+-----------+------------+
| City name | Population |
+-----------+------------+
|  Adelaide |  1158259   |
|  Brisbane |  1857594   |
|   Darwin  |   120900   |
|   Hobart  |   205556   |
|   Sydney  |  4336374   |
| Melbourne |  3806092   |
|   Perth   |  1554769   |
+-----------+------------+

选择行

使用startend参数,我们可以选择在输出中显示哪些行。

select_rows.py

#!/usr/bin/python3

from prettytable import PrettyTable

x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])

x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print(x.get_string(start=1, end=4))

在示例中,我们在输出中仅包括三行。

$ ./select_rows.py 
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
|  Brisbane | 5905 |  1857594   |      1146.4     |
|   Darwin  | 112  |   120900   |      1714.7     |
|   Hobart  | 1357 |   205556   |      619.5      |
+-----------+------+------------+-----------------+

这是示例的输出。

在本教程中,我们已使用 PrettyTable 库在 Python 中生成 ASCII 表。

您可能也会对以下相关教程感兴趣: Python CSV 教程Tkinter 教程SymPy 教程Python Pillow 教程Matplotlib 教程Python 教程



回到顶部