签到成功

知道了

CNDBA社区CNDBA社区

Python  prettytable 使用 说明

2019-08-25 17:03 3466 0 转载 Python
作者: dave

1 PrettyTable 介绍

prettytable模块是一个第三方的库,可以将输出内容如表格方式整齐输出,Pypi官方对prettytable的解释如下:

PrettyTable is a simple Python library designed to make it quick and easy to represent tabular data in visually appealing ASCII tables. It was inspired by the ASCII tables used in the PostgreSQL shell psql. PrettyTable allows for selection of which columns are to be printed, independent alignment of columns (left or right justified or centred) and printing of “sub-tables” by specifying a row range.

下载地址:
https://pypi.org/project/PrettyTable/

也可以直接使用pip进行安装:
pip install PrettyTable

如果想有更好的pip使用体验,建议使用国内的pip源:

Python 更改 PyPI 源
https://www.cndba.cn/dave/article/2261

另外注意对于python 2.6以下的版本,建议安装prettytable 0.6的版本,同样,Python 2.7+的,建议安装prettytable 0.7+的版本。

2 Prettytable 语法说明

2.1 创建表

直接创建

pt = PrettyTable()http://www.cndba.cn/dave/article/3563

从已有文件创建

http://www.cndba.cn/dave/article/3563
http://www.cndba.cn/dave/article/3563

#CSV
from prettytable import from_csv 
fp = open("mytable.csv", "r") 
pt = from_csv(fp) 
fp.close()

#HTML
from prettytable import from_html 
pts = from_html(html_string)

#SQL
from prettytable import from_db_cursor 
db_cur.execute("SELECT * FROM mytable") 
pt = from_db_cursor(db_cur)

2.2 添加元素

按行添加元素

pt.add_row()

http://www.cndba.cn/dave/article/3563

按列添加元素

http://www.cndba.cn/dave/article/3563

pt.add_column()http://www.cndba.cn/dave/article/3563

2.3 输出

直接输出

print(pt)http://www.cndba.cn/dave/article/3563

无表格框输出

print(pt.get_string())

HTML表输出:

print(pt.get_html_string())

选择子表

http://www.cndba.cn/dave/article/3563
http://www.cndba.cn/dave/article/3563

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

#输出前4列
print(pt.get_string(start = 0, end = 3))
new_table = old_table[0:3]
print(new_table)

表排序
print x.get_string(sortby="Annual Rainfall", reversesort=True)

2.4 控制表样式

2.4.1 自带样式

#参数还可以选择“DEFAULT”、“PLAIN_COLUMNS”
from prettytable import MSWORD_FRIENDLY
x.set_style(MSWORD_FRIENDLY) 
print(x)

2.4.2 手动控制样式

可调整选项如下:

选项 说明
border 布尔类型参数(必须是True或False)。控制表格边框是否显示。
header 布尔类型参数(必须是True或False)。控制表格第一行是否作为表头显示。
header-style 控制表头信息的大小写。允许的参数值:“cap”(每个单词首字母大写),“title”(除了介词助词首字母大写),“lower”(全部小写)或者None(不改变原内容格式)。默认参数为None。
hrules 设置表格内部水平边线。允许的参数值:FRAME,ALL,NONE。注意这些是在prettytable模块内部定义的变量,在使用之前导入或用类似prettytable.FRAME的方法调用。
vrules 设置表格内部竖直边线。允许的参数值:FRAME,ALL,NONE。
align 水平对齐方式(None,“l”(左对齐),“c”(居中),“r”右对齐)
valign 垂直对齐方式(None,“t”(顶部对齐),“m”(居中),“b”底部对齐)
int_format 控制整型数据的格式。
float_format 控制浮点型数据的格式。
padding_width 列数据左右的空格数量。(当左右padding未设置时生效)
left_padding_width 列数据左侧的空格数量。
right_padding_width 列数据右侧的空格数量。
vertical_char 绘制竖直边线的字符,默认为“
horizontal_char 绘制水平边线的字符,默认为“-”
junction_char 绘制水平竖直交汇点的字符,默认为“+”

用法http://www.cndba.cn/dave/article/3563

x = PrettyTable() 
x.border = False 
x.header = False 
x.padding_width = 5

x = PrettyTable(border=False, header=False, padding_width=5)

以上两种设置方式等效

调整对齐方式的几种方法

print(x.get_string(align="l"))

x.align["City name"] = "l" 
x.align["Population"] = "c" 
x.align["Area"] = "r"

x.align = "l'

3 PrettyTable 示例

import prettytable as pt

## 按行添加数据
tb = pt.PrettyTable()
tb.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
tb.add_row(["Adelaide",1295, 1158259, 600.5])
tb.add_row(["Brisbane",5905, 1857594, 1146.4])
tb.add_row(["Darwin", 112, 120900, 1714.7])
tb.add_row(["Hobart", 1357, 205556,619.5])

print(tb)

#output
ssh://root@192.168.20.15:22/usr/bin/python -u /dave/orz/test.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      |
+-----------+------+------------+-----------------+


## 按列添加数据
tb.add_column('index',[1,2,3,4])
print(tb)

#output
+-----------+------+------------+-----------------+-------+
| City name | Area | Population | Annual Rainfall | index |
+-----------+------+------------+-----------------+-------+
|  Adelaide | 1295 |  1158259   |      600.5      |   1   |
|  Brisbane | 5905 |  1857594   |      1146.4     |   2   |
|   Darwin  | 112  |   120900   |      1714.7     |   3   |
|   Hobart  | 1357 |   205556   |      619.5      |   4   |
+-----------+------+------------+-----------------+-------+

## 使用不同的输出风格
tb.set_style(pt.MSWORD_FRIENDLY)
print('--- style:MSWORD_FRIENDLY -----')
print(tb)

tb.set_style(pt.PLAIN_COLUMNS)
print('--- style:PLAIN_COLUMNS -----')
print(tb)

## 随机风格,每次不同
tb.set_style(pt.RANDOM)
print('--- style:MSWORD_FRIENDLY -----')
print(tb)

tb.set_style(pt.DEFAULT)
print('--- style:DEFAULT -----')
print(tb)

#output
--- style:MSWORD_FRIENDLY -----
| 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      |

--- style:PLAIN_COLUMNS -----
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             
--- style:MSWORD_FRIENDLY -----
@    Adelaide     1295     1158259     600.5 @
@    Brisbane     5905     1857594     1146.4@
@     Darwin      112       120900     1714.7@
@     Hobart      1357      205556     619.5 @
--- style:DEFAULT -----
+-----------+------+------------+-----------------+
| 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      |
+-----------+------+------------+-----------------+

## 不打印,获取表格字符串
s = tb.get_string()
print(s)

## prettytable也支持输出HTML代码
s = tb.get_html_string()
print(s)

## 可以只获取指定列或行
s = tb.get_string(fields=["City name", "Population"],start=1,end=4)
print(s)

#output
+-----------+------+------------+-----------------+
| 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      |
+-----------+------+------------+-----------------+
+-----------+------------+
| City name | Population |
+-----------+------------+
|  Brisbane |  1857594   |
|   Darwin  |   120900   |
|   Hobart  |   205556   |
+-----------+------------+

## 自定义表格输出样式
### 设定左对齐
tb.align = 'l'
### 设定数字输出格式
tb.float_format = "2.2"
### 设定边框连接符为'*"
tb.junction_char = "*"
### 设定排序方式
tb.sortby = "City name"
### 设定左侧不填充空白字符
tb.left_padding_width = 0
print(tb)

#output
*----------*-----*-----------*----------------*
|City name |Area |Population |Annual Rainfall |
*----------*-----*-----------*----------------*
|Adelaide  |1295 |1158259    |600.50          |
|Brisbane  |5905 |1857594    |1146.40         |
|Darwin    |112  |120900     |1714.70         |
|Hobart    |1357 |205556     |619.50          |
*----------*-----*-----------*----------------*

## 不显示边框
tb.border = 0
print(tb)

## 修改边框分隔符
tb.set_style(pt.DEFAULT)
tb.horizontal_char = '+'
print(tb)

#output
City name Area Population Annual Rainfall 
Adelaide  1295 1158259    600.50          
Brisbane  5905 1857594    1146.40         
Darwin    112  120900     1714.70         
Hobart    1357 205556     619.50          
+++++++++++++++++++++++++++++++++++++++++++++++++++
| City name | Area | Population | Annual Rainfall |
+++++++++++++++++++++++++++++++++++++++++++++++++++
| Adelaide  | 1295 | 1158259    | 600.50          |
| Brisbane  | 5905 | 1857594    | 1146.40         |
| Darwin    | 112  | 120900     | 1714.70         |
| Hobart    | 1357 | 205556     | 619.50          |
+++++++++++++++++++++++++++++++++++++++++++++++++++
用户评论
* 以下用户言论只代表其个人观点,不代表CNDBA社区的观点或立场
dave

dave

关注

人的一生应该是这样度过的:当他回首往事的时候,他不会因为虚度年华而悔恨,也不会因为碌碌无为而羞耻;这样,在临死的时候,他就能够说:“我的整个生命和全部精力,都已经献给世界上最壮丽的事业....."

  • 2261
    原创
  • 3
    翻译
  • 578
    转载
  • 191
    评论
  • 访问:7969971次
  • 积分:4346
  • 等级:核心会员
  • 排名:第1名
精华文章
    最新问题
    查看更多+
    热门文章
      热门用户
      推荐用户
        Copyright © 2016 All Rights Reserved. Powered by CNDBA · 皖ICP备2022006297号-1·

        QQ交流群

        注册联系QQ