# # Original homework solution # def ask_user(): import sys sys.stdout.write("Enter ZIP code: ") zipcode = sys.stdin.readline().strip() # Should check for valid zip code here town, population = find_zip(zipcode) print "%s -> %s (population %s)" % (zipcode, town, population) def find_zip(zipcode): import urllib conn = urllib.urlopen("http://www.uszip.com/zip/%s" % zipcode) town = "unknown" population = "unknown" for line in conn.fp: if "is the zip code of " in line: town = get_town(line) elif "Population:" in line: population = get_population(line) return town, population def get_town(line): line = strip_tags(line) key_string = "is the zip code of " try: n = line.index(key_string) except ValueError: return "unknown" else: return line[n + len(key_string):] def get_population(line): line = strip_tags(line) key_string = "Population:" try: n = line.index(key_string) except ValueError: return "unknown" else: start = n + len(key_string) stop = start + 1 while stop < len(line): if line[stop] not in "0123456789,": break stop += 1 return line[start:stop] def strip_tags(line): keep = [] in_tag = False for c in line: if in_tag: if c == '>': in_tag = False else: if c == '<': in_tag = True else: keep.append(c) return ''.join(keep).strip() ask_user()