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模块

pip install colorama

使用范例

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

现在我们使用这个类: 
修改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#返回所有车次余票信息

测试结果: 

漂亮的输出-----prettytable和colorama的使用的更多相关文章

  1. 一个漂亮的输出MySql数据库表结构的PHP页面

    经常为了方便和直观,我们会首先直接在数据库中设计出表,但是接下来又要将表的结构和设计编写在设计文档中,以便编码的时候可以直观的查询,一旦数据库表非常多,字段非常多的时候,这无疑是件非常郁闷的工作. 这 ...

  2. python改变输出字体颜色==>colorama

    colorama是python第三方库中一个可以改变输出流颜色的玩意儿, 安装可以通过: pip install colorama 简单介绍 from colorama import Fore, Ba ...

  3. Python 输出漂亮的表格的5个案例,实用方便

    文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者:程序IT圈 PS:如有需要Python学习资料的小伙伴可以加点击下方链接自行 ...

  4. Python3实现火车票查询工具

    Python 实现火车票查询工具 一. 实验介绍 通过python3实现一个简单的命令行版本的火车票查询工具,用实际中的例子会更感兴趣,不管怎么样,既练习了又可以自己使用. 1.  知识点: Pyth ...

  5. Python 实现火车票查询工具

    注意:由于 12306 的接口经常变化,课程内容可能很快过期,如果遇到接口问题,需要根据最新的接口对代码进行适当修改才可以完成实验. 一.实验简介 当你想查询一下火车票信息的时候,你还在上 12306 ...

  6. MongoDB、MySQL

    我的电脑的系统Path:   D:\sqlite;D:\Program Files\MongoDB\Server\3.4\bin;%MYSQL_HOME%\bin;D:\Program Files\B ...

  7. Python 实现的 12306抢票脚本

    Python12306抢票脚本 本脚本使用一个类来实现所有代码,大体上分为以下几个模块及其步骤:- 初始化对象属性(在抢票前进行的属性初始化,包括初始化浏览器模拟对象,个人信息等).- 建立模拟浏览器 ...

  8. Python常用的标准库以及第三方库有哪些?

    20个必不可少的Python库也是基本的第三方库 读者您好.今天我将介绍20个属于我常用工具的Python库,我相信你看完之后也会觉得离不开它们.他们是: Requests.Kenneth Reitz ...

  9. 20个必不可少的Python库也是基本的第三方库

    个属于我常用工具的Python库,我相信你看完之后也会觉得离不开它们.他们是: Requests.Kenneth Reitz写的最富盛名的http库.每个Python程序员都应该有它. Scrapy. ...

随机推荐

  1. virtualbox虚拟机Linux系统与本地windows系统共享文件方法

    转自:http://jingyan.baidu.com/article/2fb0ba40541a5900f2ec5f07.html

  2. Myeclipse下使用Maven搭建spring boot项目(第二篇)

    现在需要搭建spring boot框架,并实现一个HelloWorld的项目,让程序真正运行起来. 一.在pom.xml中引入spring-boot-start-parent,spring官方的叫st ...

  3. 7624:山区建小学(划分dp)

    7624:山区建小学 查看 提交 统计 提问 总时间限制: 1000ms 内存限制: 65536kB 描述 政府在某山区修建了一条道路,恰好穿越总共m个村庄的每个村庄一次,没有回路或交叉,任意两个村庄 ...

  4. ios笔试题(选择题)

    1-10 C语言 & 计算机基础 1.请看下面一段代码 static int a = 1; int main(){ int b = 2; char *c = NULL; c = (char * ...

  5. linux shell 脚本使用

    定义变量 fileName=text.txt 变量名称fileName,变量名称text.txt 使用变量 $fileName 用美元符号$开头,后面加变量名称,即可使用变量 使用用户输入参数 打印第 ...

  6. Spring---Bean使用外部属性文件

    在配置文件里配置 Bean 时, 有时需要在 Bean 的配置里混入系统部署的细节信息(例如: 文件路径, 数据源配置信息等). 而这些部署细节实际上需要和 Bean 配置相分离 Spring 提供了 ...

  7. Code Forces 645C Enduring Exodus

    C. Enduring Exodus time limit per test2 seconds memory limit per test256 megabytes inputstandard inp ...

  8. 阿里云OSS分片上传DEMO

    分片传输规则 1.不能超过10000片,2.每片必须大于100KB using System; using System.Collections.Generic; using System.Compo ...

  9. 污染Bootstrap modal 通过 css选择器 避免

    w 对框架的掌握.改进. 0-存在重复代码,需要改正,js timepicker框架传入类名: 1-大量的点击块,怎样避免对每个块重复写modal? <style> .w > td ...

  10. [golang]内存不断增长bytes.makeSlice

    ------------------------------------------ 2015.7月更新 后面发现这里其实有一个sb的问题,在于内存回收和释放. 每个http请求,都会带一个http. ...