Script to grab stop codes from allstops.xml and sort
[ottawa-travel-planner.git] / ShortFormatter.py
blobd957355c196a72072c0a229dd45d7814feeece84
2 # vi: set softtabstop=4 shiftwidth=4 tabstop=8 expandtab:
4 """Formats an Itinerary for terse display."""
6 import re
8 import Itinerary
10 class ShortFormatter:
11 def __init__(self, itinentries):
12 self.entries = itinentries
14 # A list of text strings to display.
15 self.lines = []
17 self.format()
19 def format(self):
20 for ie in self.entries:
21 if ie.type == Itinerary.TYPE_WALK_TO_STOP:
22 self.formatWalkToStop(ie)
23 elif ie.type == Itinerary.TYPE_TAKE_BUS:
24 self.formatTakeBus(ie)
25 elif ie.type == Itinerary.TYPE_WALK_TO_TRANSFER:
26 self.formatWalkToTransfer(ie)
27 elif ie.type == Itinerary.TYPE_WALK_TO_DEST:
28 self.formatWalkToDest(ie)
30 def formatWalkToStop(self, ie):
31 line = "-%s walk %s (%s)" \
32 % (self.canonTime(ie.startTime),
33 self.canonDest(ie.destination), ie.busStop)
34 self.lines.append(line)
36 def formatTakeBus(self, ie):
37 line = "-%s %s %s to %s at %s" \
38 % (self.canonTime(ie.startTime), ie.route,
39 self.canonDirection(ie.direction),
40 self.canonDest(ie.destination),
41 self.canonTime(ie.endTime))
42 self.lines.append(line)
44 def formatWalkToTransfer(self, ie):
45 line = "-walk %s (%s)" % (self.canonDest(ie.destination), ie.busStop)
46 self.lines.append(line)
48 def formatWalkToDest(self, ie):
49 line = "-walk %s %s" \
50 % (self.canonDest(ie.destination), self.canonTime(ie.endTime))
51 self.lines.append(line)
53 def canonDest(self, d):
54 """MERIVALE / COLONNADE -> Merivale/Colonnade"""
55 match = _canon_dest_rx.match(d)
56 if match:
57 d = "/".join((match.group(1), match.group(2)))
59 # Hurdman Stop/Arret 2A -> Hurdman 2A
60 d = _arret_rx.sub("", d)
61 return d.title()
63 def canonTime(self, t):
64 """11:05 AM -> 11:05"""
65 return t.split()[0]
67 def canonDirection(self, d):
68 """St Laurent -> St Lau. Take the first 3 letters of all words
69 after the first."""
70 words = d.split()
71 canonwords = [words[0]]
72 for w in words[1:]:
73 canonwords.append(w[0:3]) # ok even if only 2 letters in w
74 return " ".join(canonwords)
76 def __str__(self):
77 return "\n".join(self.lines)
79 def __repr__(self):
80 print self.__str__()
82 _canon_dest_re = "^(.*)\s/\s+(.*)$"
83 _canon_dest_rx = re.compile(_canon_dest_re)
85 _arret_re = r"(?i)\s*Stop/Arr..\b"
86 _arret_rx = re.compile(_arret_re)