#!/usr/bin/python # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ import sys import re """Baby Names exercise Define the extract_names() function below and change main() to call it. For writing regex, it's nice to include a copy of the target text for inspiration. Here's what the html looks like in the baby.html files: ...

Popularity in 1990

.... 1MichaelJessica 2ChristopherAshley 3MatthewBrittany ... Suggested milestones for incremental development: -Extract the year and print it -Extract the names and rank numbers and just print them -Get the names data into a dict and print it -Build the [year, 'name rank', ... ] list and print it -Fix main() to use the extract_names list """ def extract_names(filename): """ Given a file name for baby.html, returns a list starting with the year string followed by the name-rank strings in alphabetical order. ['2006', 'Aaliyah 91', Aaron 57', 'Abagail 895', ' ...] """ # +++your code here+++ name = [] # read the file f = open(filename,'rU') text = f.read() # get the year get_year = re.search(r'Popularity\sin\s(\d\d\d\d)',text) if get_year: name.append(get_year.group(1)) else: sys.stderr.write('Couldn\'t find the year!\n') sys.exit(1) # get names tuples = re.findall(r'(\d+)(\w+)\(\w+)', text) name_rank = {} for name_tuple in tuples: (rank,boyname,girlname) = name_tuple if boyname not in name_rank: name_rank[boyname] = rank if girlname not in name_rank: name_rank[girlname] = rank name_ranked = sorted(name_rank.iteritems(),key=lambda name_rank:name_rank[0]) for rank_name in name_ranked: name.append(rank_name[0]+' '+rank_name[1]) f.close() return name def main(): # This command-line parsing code is provided. # Make a list of command line arguments, omitting the [0] element # which is the script itself. args = sys.argv[1:] if not args: print 'usage: [--summaryfile] file [file ...]' sys.exit(1) # Notice the summary flag and remove it from args if it is present. summary = False if args[0] == '--summaryfile': summary = True del args[0] # +++your code here+++ # For each filename, get the names, then either print the text output # or write it to a summary file for filename in args: text = extract_names(filename) text = '\n'.join(text) if summary: outf = open(filename + '.summary', 'w') outf.write(text + '\n') outf.close() else: print text if __name__ == '__main__': main()