pythontabulate - 介绍和使用

发布时间:2023-05-20

一、简介

pythontabulate 是一款基于 Python 的包,它用于将各种数据以美观的表格形式打印(ASCII,Markdown,HTML等)。如果你需要将数据格式化为表格数据,这可能是您需要的最后一个库。它具有许多功能,例如:自定义表头,对其方式,精确小数位数,列宽以及列优先级等。它还支持对字典和数组等数据类型进行表格化。该库的安装方法很容易:

pip3 install tabulate

二、表格的不同格式

首先让我们看看该库可以在三种格式中格式化表格:

  • ASCII格式:
+----+-------+-----------+
| id | name  |    age    |
+----+-------+-----------+
| 1  | Alice |    20     |
| 2  | Bob   |   **30**    |
+----+-------+-----------+
  • Markdown 格式:
| id | name  |    age    |
|----|-------|-----------|
| 1  | Alice |    20     |
| 2  | Bob   |   **30**    |
  • HTML 格式:
<table>
  <thead>
    <tr>
      <th>id</th>
      <th>name</th>
      <th>age</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Alice</td>
      <td>20</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Bob</td>
      <td><b>30</b></td>
    </tr>
  </tbody>
</table>

三、使用 pythontabulate

为了使用用 pythontabulate 打印表格,我们必须先将要打印的数据存储为数组或字典形式:

from tabulate import tabulate
data = [['Alice', 20], ['Bob', 30]]
headers = ['name', 'age']
print(tabulate(data, headers, tablefmt='psql'))

这将生成以下的表格:

+-------+-----+
| name  | age |
|-------+-----|
| Alice |  20 |
| Bob   |  30 |
+-------+-----+

在这个例子中,我们传递了数据和标题参数,然后使用 psqsl 表格格式。该 tablefmt 参数可以是“plain”、“simple”、“github”、“grid”等格式。

四、自定义列优先级、对齐方式和格式

除了标题和数据外,我们还可以设置列的对齐方式和列的格式。下面是一个包括所有选项的示例:

data = [
    ['Alice', 20, 123456.789],
    ['Bob is really cool', 30, 234567.890],
    ['Charlie', 40, 345678.901]
]
headers = ['name', 'age', 'num']
print(tabulate(data, headers=headers, tablefmt="psql", numalign="decimal", stralign="center", floatfmt=".2f"))

这将生成以下的表格:

+------------------+-----+------------+
|       name       | age |    num     |
|------------------+-----+------------|
|      Alice       |  20 |  123456.79 |
| Bob is really cool|  30 | 234567.89  |
|     Charlie      |  40 | 345678.90  |
+------------------+-----+------------+

在此示例中,我们在表单中使用标题和数据进行表格化,然后使用 psqsl 表格格式,并使用 numalign、stralign 和 floatfmt 参数进行对齐和格式设置。使用 numalign 和 stralign 参数,您可以分别设置数字和字符串的对齐方式。floatfmt 参数用于格式化表格中的浮点数。

五、其他示例

有关更多示例,请参阅以下代码和结果:

# 字典 row 方式打印
data = [{'name': 'Alice', 'age': 20}, {'name': 'Bob', 'age': 30}]
print(tabulate(data, headers='keys', tablefmt='psql'))
# 打印 CSV 格式文件
import csv
with open('data.csv') as f:
    reader = csv.reader(f)
    data = [row for row in reader]
    print(tabulate(data, headers='firstrow'))
# 纵向打印数据
data = [['Alice', 20], ['Bob', 30]]
print(tabulate(data, tablefmt='plain', showindex=True))
# 简单数据表
data = [['Alice', 20], ['Bob', 30]]
print(tabulate(data))
# 没有表头的简单表格式
data = [['Alice', 20], ['Bob', 30]]
print(tabulate(data, headers=['Name', 'Age'], tablefmt='plain'))

pythontabulate是一款十分实用的Python库,可以方便快捷地将数据格式化为美观的表格。这为数据分析提供了便利和可视化的解决方法。记得去官网查看更多内容。