Last active 1440821022

Transperth offline bus stop data and example implementation

Revision 5b7e4f1430706536daa8f915dddcea7aac9a46dc

tpparse.py Raw
1# Data can be retrieved (gzipped) from https://mega.co.nz/#!os4gjQBR!fspHcvoHZHDzN6IGtJgIXUh4N_ciIEL40tHoivqcKXg
2# Currently this data only contains info for weekdays, as of 2014-06-20. I can't make the data
3# collection process public, sadly, so please email me if you'd like saturday or sunday/holiday data.
4#
5# This is an example implementation of a program to read this data, in Python
6# It replicates Transperth's service to look up the next five bus times to a stop, as seen here
7# http://136213.mobi/Bus/StopResults.aspx?SN=14353
8# Please direct questions to steven+transperthdata@blha303.com.au
9#
10# Example output, recorded at 6:18am on a Wednesday:
11# $ tpparse.py 14353
12# 06:24: 39
13# 06:45: 39
14# 07:26: 39
15# 07:36: 39
16# 07:48: 39
17
18import json,gzip,datetime,sys
19
20def get_data():
21 with gzip.open('transperthcache.json.gz', 'rb') as f:
22 data = json.load(f)
23 return data
24
25def daycheck(date=False):
26 """For getting the correct timetable from [[weekday], [sat], [sun]]"""
27 now = date if date else datetime.datetime.now()
28 if now.isoweekday() in range(1,6):
29 return 0
30 elif now.isoweekday() in range(6,7):
31 return 1
32 elif now.isoweekday() in range(7,8):
33 return 2
34
35def next_five(data, stop, date=False):
36 """For getting the next five stops from the specified time (by default, now)"""
37 now = date if date else datetime.datetime.now()
38 try:
39 stop = str(int(stop)) # sanity checks
40 except ValueError:
41 return u"Invalid stop number: " + unicode(stop)
42 if not stop in data:
43 return unicode(stop) + u" not found in cache"
44 x = 0
45 out = u""
46 for i in data[stop][daycheck()]:
47 if x > 4:
48 break
49 if int(i[1][:2]) >= now.hour:
50 if int(i[1][3:]) >= now.minute:
51 out = out + u"{}: {}\r\n".format(i[1], i[0])
52 x += 1
53 return out.strip() if x else "No results"
54
55if __name__ == "__main__":
56 if len(sys.argv) > 1:
57 stop = sys.argv[1]
58 else:
59 stop = "14353"
60 print(next_five(get_data(), stop))
61