def colored(color, text): table = { 'red': '\033[91m', 'green': '\033[92m', 'nc': '\033[0m' } cv = table.get(color) nc = table.get('nc') return ''.join([cv, text, nc]) class TrainCollection(object): header = '显示车次 出发/到达站 出发/到达时间 历时 一等坐 二等坐 软卧 硬卧 硬座'.split() def __init__(self, rows): self.rows = rows def _get_duration(self, row): """ 获取车次运行时间 """ duration = row.get('lishi').replace(':', 'h') + 'm' if duration.startswith('00'): return duration[4:] if duration.startswith('0'): return duration[1:] return duration @property def trains(self): for row in self.rows: train = [ row['station_train_code'], '\n'.join([colored('green', row['from_station_name']),colored('red', row['to_station_name'])]), '\n'.join([colored('green', row['start_time']),colored('red', row['arrive_time'])]), self._get_duration(row), row['zy_num'], row['ze_num'], row['rw_num'], row['yw_num'], row['yz_num'] ] yield train def pretty_print(self): pt = PrettyTable() pt._set_field_names(self.header) for train in self.trains: pt.add_row(train) print(pt)
|