Last active
August 29, 2015 14:03
-
-
Save blha303/6b0b3c836c3c6edbbf68 to your computer and use it in GitHub Desktop.
Transperth offline bus stop data and example implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Data can be retrieved (gzipped) from | |
# https://mega.co.nz/#!os4gjQBR!fspHcvoHZHDzN6IGtJgIXUh4N_ciIEL40tHoivqcKXg | |
# Currently this data only contains info for weekdays, as of 2014-06-20. I can't make the data | |
# collection process public, sadly, so please email me if you'd like saturday or sunday/holiday data. | |
# | |
# This is an example implementation of a program to read this data, in Python | |
# It replicates Transperth's service to look up the next five bus times to a stop, as seen here | |
# http://136213.mobi/Bus/StopResults.aspx?SN=14353 | |
# Please direct questions to steven+transperthdata@blha303.com.au | |
# | |
# Example output, recorded at 6:18am on a Wednesday: | |
# $ tpparse.py 14353 | |
# 06:24: 39 | |
# 06:45: 39 | |
# 07:26: 39 | |
# 07:36: 39 | |
# 07:48: 39 | |
import json,gzip,datetime,sys | |
def get_data(): | |
with gzip.open('transperthcache.json.gz', 'rb') as f: | |
data = json.load(f) | |
return data | |
def daycheck(date=False): | |
"""For getting the correct timetable from [[weekday], [sat], [sun]]""" | |
now = date if date else datetime.datetime.now() | |
if now.isoweekday() in range(1,6): | |
return 0 | |
elif now.isoweekday() in range(6,7): | |
return 1 | |
elif now.isoweekday() in range(7,8): | |
return 2 | |
def next_five(data, stop, date=False): | |
"""For getting the next five stops from the specified time (by default, now)""" | |
now = date if date else datetime.datetime.now() | |
try: | |
stop = str(int(stop)) # sanity checks | |
except ValueError: | |
return u"Invalid stop number: " + unicode(stop) | |
if not stop in data: | |
return unicode(stop) + u" not found in cache" | |
x = 0 | |
out = u"" | |
for i in data[stop][daycheck()]: | |
if x > 4: | |
break | |
if int(i[1][:2]) >= now.hour: | |
if int(i[1][3:]) >= now.minute: | |
out = out + u"{}: {}\r\n".format(i[1], i[0]) | |
x += 1 | |
return out.strip() if x else "No results" | |
if __name__ == "__main__": | |
if len(sys.argv) > 1: | |
stop = sys.argv[1] | |
else: | |
stop = "14353" | |
print(next_five(get_data(), stop)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment