Created
March 7, 2012 18:36
-
-
Save jaysoffian/1995010 to your computer and use it in GitHub Desktop.
Modern pythonic solution to http://code.google.com/edu/languages/google-python-class/exercises/baby-names.html
This file contains hidden or 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
#!/usr/bin/python | |
import sys | |
import re | |
def extract_names(path): | |
year = None | |
ranks = {} | |
def add_rank(name, rank): | |
# add name to ranks if its not already present or if its smaller | |
if name not in ranks or rank < ranks[name]: | |
ranks[name] = rank | |
with open(path) as f: | |
for line in f: | |
m = re.search(r'Popularity in (\d{4})', line) | |
if m: | |
year = m.group(1) | |
continue | |
m = re.search( | |
r'<td>(\d+)</td><td>([^<]+)</td><td>([^<]+)</td>', line) | |
if m: | |
rank, male_name, female_name = m.groups() | |
rank = int(rank) | |
add_rank(male_name, rank) | |
add_rank(female_name, rank) | |
return [year] + sorted("%s %s" % t for t in ranks.items()) | |
def main(args): | |
summarize = '--summaryfile' in args | |
if summarize: | |
args.remove('--summaryfile') | |
for arg in args: | |
summary = '\n'.join(extract_names(arg)) | |
if summarize: | |
with open(arg + '.summary', 'w') as f: | |
f.write(summary + '\n') | |
else: | |
print summary | |
if __name__ == '__main__': | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should probably not continue to search for year once its been found.