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

 

 

前言

 

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

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

查看源码:更新微信 7.0,你后悔了吗?

☞ 程序员求助:被领导强行要求写Bug该怎么办?网友的回答让我笑翻

☞ 20k~65k, 2018年最后一波热门技术岗位, 立刻投简历, 跳槽才是加薪的捷径

何恺明等最新突破:视频识别快慢结合,取得人体动作AVA数据集最佳水平

 霸气!女程媛征男友的需求说明书!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值