Python通过prettytable模块将输出内容如表格方式整齐输出,python本身并不内置,需要独立安装该第三方库。
1 pip install PrettyTable
1 #源码安装 2 wget https://pypi.python.org/packages/source/P/PrettyTable/prettytable-0.7.2.tar.gz 3 tar -zxvf prettytable-0.7.2.tar.gz 4 python setup.py build 5 python setup.py install
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)
+-----------+------+------------+-----------------+
| 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)
+-----------+------+------------+-----------------+-------+
| 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)
--- 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)
## 可以只获取指定列或行
s = tb.get_string(fields=["City name", "Population"],start=1,end=4)
print(s)
+-----------+------+------------+-----------------+
| 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)
*----------*-----*-----------*----------------*
|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)
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 |
+++++++++++++++++++++++++++++++++++++++++++++++++++
## prettytable也支持输出HTML代码
s = tb.get_html_string()
print(s)
colorama是一个python专门用来在控制台、命令行输出彩色文字的模块,可以跨平台使用。
1. 安装colorama模块
1 |
pip install colorama
|
可用格式常数:
1 2 3 |
Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Style: DIM, NORMAL, BRIGHT, RESET_ALL
|
colorama是一个python专门用来在控制台、命令行输出彩色文字的模块,可以跨平台使用,在windows下linux下都工作良好,如果你想让控制台的输出信息更漂亮一些,可以使用给这个模块。
colorama官方地址:https://pypi.python.org/pypi/colorama
安装colorama模块
1 |
pip install colorama
|
使用范例
1 |
from colorama import init,Fore init(autoreset = True ) #通过使用autoreset参数可以让变色效果只对当前输出起作用,输出完成后颜色恢复默认设置 print(Fore.RED + 'welcome to www.jb51.net') print('automatically back to default color again')
|
这段代码可以将 welcome to www.jb51.net 字符串以红色输出到控制台
创建一个专门用于更改颜色的类Colored并且添加相应方法:
from colorama import init, Fore, Back, Style
init(autoreset=False)
class Colored(object):
# 前景色:红色 背景色:默认
def red(self, s):
return Fore.LIGHTRED_EX + s + Fore.RESET
# 前景色:绿色 背景色:默认
def green(self, s):
return Fore.LIGHTGREEN_EX + s + Fore.RESET
def yellow(self, s):
return Fore.LIGHTYELLOW_EX + s + Fore.RESET
def white(self,s):
return Fore.LIGHTWHITE_EX + s + Fore.RESET
def blue(self,s):
return Fore.LIGHTBLUE_EX + s + Fore.RESET
现在我们使用这个类:
修改resolveData()函数的部分代码:
def resolveData():
#查询链接
url = 'https://kyfw.12306.cn/otn/leftTicket/queryO?leftTicketDTO.train_date=2018-01-31&leftTicketDTO.from_station=XAY&leftTicketDTO.to_station=GZG&purpose_codes=ADULT' #获取数据
while 1:
try:
data = getData(url)
lists = json.loads(data)["data"]["result"]
break
except:
continue
cont = []
name = [
"station_train_code",
"from_station_name",
'start_time',
"lishi",
"swz_num",
"zy_num",
"ze_num",
"gr_num",
"rw_num",
"dw_num",
"yw_num",
"rz_num",
"yz_num",
"wz_num",
"qt_num",
"note_num"
]
color = Colored()#创建Colored对象
for items in lists:#遍历result的每一项
#data字典用于存放每一车次的余票信息
data = {
"station_train_code": '',
"from_station_name": '',
"to_station_name": '',
'start_time': '',
'end': '',
"lishi": '',
"swz_num": '',
"zy_num": '',
"ze_num": '',
"dw_num": '',
"gr_num": '',
"rw_num": '',
"yw_num": '',
"rz_num": '',
"yz_num": '',
"wz_num": '',
"qt_num": '',
"note_num": ''
}
item = items.split('|')#用"|"进行分割
data['station_train_code'] = item[3]#车次在3号位置
data['from_station_name'] = item[6]#始发站信息在6号位置
data['to_station_name'] = item[7]#终点站信息在7号位置
data['start_time'] = item[8]#出发时间信息在8号位置
data['arrive_time'] = item[9]#抵达时间在9号位置
data['lishi'] = item[10]#经历时间在10号位置
data['swz_num'] = item[32] or item[25]# 特别注意:商务座在32或25位置
data['zy_num'] = item[31]#一等座信息在31号位置
data['ze_num'] = item[30]#二等座信息在30号位置
data['gr_num'] = item[21]#高级软卧信息在31号位置
data['rw_num'] = item[23]#软卧信息在23号位置
data['dw_num'] = item[27]#动卧信息在27号位置
data['yw_num'] = item[28]#硬卧信息在28号位置
data['rz_num'] = item[24]#软座信息在24号位置
data['yz_num'] = item[29]#硬座信息在29号位置
data['wz_num'] = item[26]#无座信息在26号位置
data['qt_num'] = item[22]#其他信息在22号位置
if item[0] == 'null':
data['note_num'] = item[1]
else:
data['note_num'] = color.white(item[1])#加高亮白色
#如果没有信息则用“-”代替
for pos in name:
if data[pos] == '':
data[pos] = '-'
cont.append(data)
tickets = []#存放所有车次的余票信息
#格式化添加进tickets中
for x in cont:
tmp = []
for y in name:
if y == "from_station_name":
s = color.green(stations2CN[x[y]]) + '\n' + color.red(stations2CN[x["to_station_name"]])#始发站绿色,终点站红色
tmp.append(s)
elif y == "start_time":
s = color.green(x[y]) + '\n' + color.red(x["arrive_time"])
tmp.append(s)
elif y == "station_train_code":
s = color.yellow(x[y])
tmp.append(s)
else:
tmp.append(x[y])
tickets.append(tmp)
return tickets#返回所有车次余票信息
POWERSHELL 折叠 复制 全屏
测试结果: