# # Converted from homework solution to use modules # def find_zip(zipcode): """Return town and population for "zipcode" by querying uszip.com""" import urllib conn = urllib.urlopen("http://www.uszip.com/zip/%s" % zipcode) town = "unknown" population = "unknown" for line in conn: if "is the zip code of " in line: town = _get_town(line) elif "Population:" in line: population = _get_population(line) conn.close() return town, population def _get_town(line): """Extract town name if present""" 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): """Extract population if present""" 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): """Remove HTML tags from string, leaving only "real" text""" 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()