1. 程式人生 > >春運渡劫!Python給我搶回家的火車票

春運渡劫!Python給我搶回家的火車票

640?wx_fmt=jpeg


簡介:本文首發於個人公眾號「視學演算法」,作者阿廣,一個專注於大資料、人工智慧和演算法的學習平臺,也是一個保送中科院軟體研究所直博生的自留地。人生苦短,我願做您最忠實的技術支援夥伴!一起用程式碼改變世界!

前言

年味越來越淡,但我對過年的期待一直沒變。為了理想,離開家鄉。這一路,背上行囊,穿過人潮,千里迢迢。疲憊也好,激動也罷,總有家鄉值得牽掛。

但是,所有的鄉愁和感傷,最好的解藥就是一張火車票。每當萬事俱備,總是隻欠東風,我依然是被一張 5mm 厚的火車票攔在了門外。隱隱約約在我眼前出現,然後又悄無聲息的走掉,說的就是你,我花錢加速都搶不到的火車票。所以阿廣今天教大家如何用 Python 搶火車票!解決你的鄉情、愛情、友情,說不定還有基情?

資料介紹

12306 官方部分資料如下:

640?wx_fmt=png

實現過程

注:具有自然語言識別處理功能

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


       112號 濟南到兗州的高鐵票
       output:
       [{'entity': [[03'time'], [34'location'], [56'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 濟南 兗州 20190112
ibot 本週天從濟南迴老家兗州,幫我看下
ibot 本週五從兗州出發,打算去北京撿垃圾,幫我看下有沒有車票
ib 這週六從南京回武夷山老家,幫我看下車票
...

查詢結果並搶票

640?wx_fmt=png

寫在最後

自從學了計算機,每逢思鄉之情冉冉升起,只能通過加快敲擊鍵盤的速度來忘記此時此刻的烽火三月、家書萬金。

盼望著,盼望著,寒假來了,春天的腳步近了。在我們童顏尚駐時,過年缺少不了的部分就是走親戚,有魚肉之果腹,亦有無案牘之勞形。可後來的後來,我們長大了,走親戚在無形之中成了一種“煩惱”。

明生活不止眼前的苟且,還有往後餘生的苟且,可礙於面子,我們依然裝作不但有詩和遠方,還要有錢途的樣子。

果把過年比作愛情,那豈是:長街長,煙花繁,你挑燈回看;短亭短,紅塵輾,我把蕭再嘆?通俗點講,我願用三生煙火,換你一張通往家鄉的火車票。

——致此刻遠在他鄉奮鬥的你們

(*本文為AI科技大本營轉載文章,轉載請聯絡原作者)


推薦


640?wx_fmt=jpeg


推薦閱讀

640?wx_fmt=png