后端开发 \ Python \ 春运渡劫?Python 帮你 12306 抢回家的火车票!

春运渡劫?Python 帮你 12306 抢回家的火车票!

总点击133
简介: 前言年味越来越淡,但我对过年的期待一直没变。为了理想,离开家乡。这一路,背上行囊,穿过人潮,千里迢迢。疲惫也好,激动也罢,总有家乡值得牵挂。但是,所有的乡愁和感伤,最好的解药就是一张火车票。每当

 

前言

年味越来越淡,但我对过年的期待一直没变。为了理想,离开家乡。这一路,背上行囊,穿过人潮,千里迢迢。疲惫也好,激动也罢,总有家乡值得牵挂。

但是,所有的乡愁和感伤,最好的解药就是一张火车票。每当万事俱备,总是只欠东风,我依然是被一张 5mm 厚的火车票拦在了门外。隐隐约约在我眼前出现,然后又悄无声息的走掉,说的就是你,我花钱加速都抢不到的火车票。所以阿广今天教大家如何用 Python 抢火车票!解决你的乡情、爱情、友情,说不定还有基情?

数据介绍

12306 官方部分数据如下:

春运渡劫?Python 帮你 12306 抢回家的火车票!

春运渡劫?Python 帮你 12306 抢回家的火车票!


实现过程

注:具有自然语言识别处理功能

(1) 加载头文件

from distutils.log import warn as printf
import sys
from bosonnlp import BosonNLP
import yaml
from os.path import expanduser
import os
import collections
import subprocess
import datetime

(2) 加载配置文件

home = expanduser("~")
with open(os.path.join(home,".ibot.yml")) as f:
config = yaml.load(f)
bosonnlp_token = config["token"]

(3) 解析字符串

def parse(self, query_string):
"""       
input:
1月12号 济南到兖州的高铁票       
output:
[{'entity': [[0, 3, 'time'], [3, 4, 'location'], [5, 6, 'location']], # 需要理解实体出现的模式,这块需要理解上下文       
'tag': ['t', 'm', 'q', 'ns', 'p', 'ns', 'ude', 'n', 'n'],        
'word': ['1月', '12', '号', '济南', '到', '兖州', '的', '硬座', '票']}]       
"""
result = self.nlp.ner(query_string)[0]words = result['word']tags = result['tag']entities = result['entity']return (words,entities,tags)

(4) 获得已识别的实体

def get_entity(self,parsed_words,index_tuple):
"""       
获取已识别的实体       
采用filter       
参考 python cookbook部分       
input:           
entities :
 二元组           
 parsed_words : 
 解析好的词组       
 """
 return parsed_words[index_tuple[0]:index_tuple[1]]

(5) 元组重新命名

def format_entities(self,entities):
"""       
给元组命名       
"""
namedentity = collections.namedtuple('namedentity','index_begin index_end entity_name')return [namedentity(entity[0],entity[1],entity[2]) for entity in entities]

(6) 获取解析时间戳

def get_format_time(self,time_entity):
"""       
output       
{'timestamp': '2018-12-20 23:30:29', 'type': 'timestamp'}       
"""
basetime = datetime.datetime.today()result = self.nlp.convert_time(time_entity,basetime)#print(result)timestamp = result["timestamp"]return timestamp.split(" ")[0]

查看源码:https://github.com/zandaoguang/MissHome

 

如何调用?

iquery 济南 兖州 20190112ibot 本周天从济南回老家兖州,帮我看下ibot 本周五从兖州出发,打算去北京捡垃圾,帮我看下有没有车票ib 这周六从南京回武夷山老家,帮我看下车票...

查询结果并抢票

春运渡劫?Python 帮你 12306 抢回家的火车票!

写在最后

自从学了计算机,每逢思乡之情冉冉升起,只能通过加快敲击键盘的速度来忘记此时此刻的烽火三月、家书万金。

盼望着,盼望着,寒假来了,春天的脚步近了。在我们童颜尚驻时,过年缺少不了的部分就是走亲戚,有鱼肉之果腹,亦有无案牍之劳形。可后来的后来,我们长大了,走亲戚在无形之中成了一种“烦恼”。

明生活不止眼前的苟且,还有往后余生的苟且,可碍于面子,我们依然装作不但有诗和远方,还要有钱途的样子。

果把过年比作爱情,那岂是:长街长,烟花繁,你挑灯回看;短亭短,红尘辗,我把萧再叹?通俗点讲,我愿用三生烟火,换你一张通往家乡的火车票。

——致此刻远在他乡奋斗的你们

意见反馈 常见问题 官方微信 返回顶部