1. 程式人生 > >漂亮的輸出-----prettytable和colorama的使用

漂亮的輸出-----prettytable和colorama的使用

server 紅色 ade 使用 背景 ticket start south 完成

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的使用