python判断火车票座位_Python3 实现火车票查询工具

首先,感谢实验楼的平台。为我们这些小白提供了学习的平台。其次针对这个项目来说的话,其实算是思路比较简单的。无非就是查询然后展示。不过里面涉及到的东西是很多的,比如编码的转换、类和函数、yeilde、。.join的用法等等。总之我在做的过程中碰到了比较多的问题,然后挨着百度解决。对巩固基础知识是相当有益的。还有,实验文档中的代码有错误的部分。话不多少,贴一下我的实验结果。代码显得很冗长,比较新手:

#coding:utf-8

import re

import urllib2

import json

from prettytable import PrettyTable

class TrainCollection(object):

# 显示车次、出发\到达站、出发\到达时间、历时、一等座、二等座、软卧、硬卧、硬座

#header = "train station time duration first second softsleep hardsleep hardsit".split()

header = u"车次 出发\到达站 出发\到达时间 历时 一等座 二等座 软卧 硬卧 硬座".split()

def init(self, aabb):

self.aabb = aabb

def _get_duration(self, row):

# 获取车的历时时间

duration = row.get("lishi").replace(":", u"小时") + u"分钟"

if duration.startswith("00"):

return duration[4:]

if duration.startswith("0"):

return duration[1:]

return duration

@property

def trains(self):

for row in self.aabb:

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):

"""

数据已经获取到了,剩下的就是提取我们要的信息并将它显示出来。

`prettytable`这个库可以让我们它像MySQL数据库那样格式化显示数据。

"""

pt = PrettyTable()

# 设置每一列的标题

pt._set_field_names(self.header)

for train in self.trains:

pt.add_row(train)

print(pt)

def cli():

#获取车站资源的网站

url="https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.8955"

req=urllib2.Request(url)

#添加消息头

req.add_header=("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.1.14) Gecko/20080404 (FoxPlus) Firefox/2.0.0.14")

content=urllib2.urlopen(req).read()

#print content

#diction1={}

diction2={}

#正则表达式匹配出想地名和代码

r=r"|?\W{6,18}|?[A-Z]{3}"

stations=re.findall(r,content)

#print stations

for i in stations:

i1=i.split("|")

#将字符转换成unicode码。

i2=i1[1].decode("utf-8")

#i2=i1[1]

diction1={i2:i1[2]}

diction2.update(diction1)

'''start=raw_input("请输入成都:")

start1=start.decode("utf-8")

print start1

print diction2[start1]

上面是从链接里获取车站资源。

下面输入车站名称直接获取车站代码

并拼接到查询车次的链接里面'''

#需要输入的参数

date=raw_input(u"请输入出发日期(yyyy-mm-dd):")

start=raw_input(u"请输入出发站:")

end=raw_input(u"请输入到达站:")

print date,start,end

#获取车站代码

if diction2.has_key(start.decode("utf-8"))==True:

startcode=diction2[start.decode("utf-8")]

else:

print "查询不到出发站"

if diction2.has_key(end.decode("utf-8"))==True:

endcode=diction2[end.decode("utf-8")]

else:

print "查询不到到达站"

print startcode,endcode

#查票链接

url1="https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate="+date+"&from_station="+startcode+"&to_station="+endcode

#print url1

req1=urllib2.Request(url1)

req1.add_header=("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.1.14) Gecko/20080404 (FoxPlus) Firefox/2.0.0.14")

content1=urllib2.urlopen(req1).read()

#print type(content1)

#print content1

dic1=json.loads(content1)

aabb=dic1["data"]["datas"]

#print type(aabb)

#print aabb

trains = TrainCollection(aabb)

trains.pretty_print()

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])

if name=="main":

cli()

运行效果图:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值