我直接把代码移进的 view,然后用的一个函数调用这个类 class TrainsCollection: header = '车次 车站 时间 历时 一等 二等 软卧 硬卧 硬座 无座'.split()
def __init__(self, available_trains, options):
"""
:param available_trains: 官网提取到的 json 数据列表
:param options: 查询的选项, 如高铁, 动车, etc...
"""
self.available_trains = available_trains
self.options = options
"""切割"""
def _cut_train(self):
saperated_info = []
for i in range(len(self.available_trains)):
saperated_info.append((self.available_trains[i]).split('|'))
"""构建字典列表"""
dict_header = ['train_number', 'from_station', 'to_station', 'from_time', 'to_time', 'spend_time',
'first_class', 'second_class', 'soft_sleeper', 'hard_sleeper', 'hard_seat', 'none_seat']
refer_to_num = [3, 4, 5, 8, 9, 10, 31, 30, 23, 26, 28, 29]
train_list = []
train_dict = {}
for times in range(len(saperated_info)):
for key in range(len(dict_header)):
if saperated_info[times][refer_to_num[key]]:
train_dict[dict_header[key]] = saperated_info[times][refer_to_num[key]]
else:
train_dict[dict_header[key]] = '--'
train_list.append(copy.deepcopy(train_dict))
return train_list
@property
def trains(self):
for raw_train in self._cut_train():
train_no = raw_train['train_number']
initial = train_no[0].lower()
if not self.options or initial in self.options:
train = [
train_no,
'\n'.join([Fore.GREEN + _get_keys(raw_train['from_station']) + Fore.RESET,
Fore.RED + _get_keys(raw_train['to_station']) + Fore.RESET]),
'\n'.join([Fore.GREEN + raw_train['from_time'] + Fore.RESET,
Fore.RED + raw_train['to_time'] + Fore.RESET]),
raw_train['spend_time'],
raw_train['first_class'],
raw_train['second_class'],
raw_train['soft_sleeper'],
raw_train['hard_sleeper'],
raw_train['hard_seat'],
raw_train['none_seat'],
]
yield train
def _get_keys(station_eg):
for key in stations:
if stations[key] == station_eg:
def pretty_print(self):
pt = PrettyTable()
pt._set_field_names(self.header)
for train in self.trains:
pt.add_row(train)
content = PrettyTable.whatever()
return HttpResponse('<pre>{}</pre>'.format(content))
错误提示: def pretty_print(self): ^ IndentationError: expected an indented block
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.