1 # Q: Instead of "binning" your dataset by day, change to bin it by month for each of the two previous questions.
3 # This is a modified version of solution4.py. Changing solution3.py
6 from csv import DictReader
8 # STEP 1: read in the input file and count by article
9 input_file = open("hp_wiki.tsv", 'r', encoding="utf-8")
12 for row in DictReader(input_file, delimiter="\t"):
15 if title in edits_by_article:
16 edits_by_article[title] = edits_by_article[title] + 1
18 edits_by_article[title] = 1
23 # STEP 2: find the list of the top 3 articles
25 for title in sorted(edits_by_article, key=edits_by_article.get, reverse=True):
26 if len(top_articles) >= 3:
29 top_articles.append(title)
32 # STEP 3: now, fill that by doing a version of the first count by
33 # going back through the original data and this time just count each
34 # of the three articles
36 article_edits_by_month = {}
38 input_file = open("hp_wiki.tsv", 'r', encoding="utf-8")
39 for row in DictReader(input_file, delimiter="\t"):
42 if title not in top_articles:
45 # NOTE: this line is the key difference
46 month = row['timestamp'][0:7]
48 if month in article_edits_by_month:
49 article_edits_by_month[month][title] = article_edits_by_month[month][title] + 1
51 article_edits_by_month[month] = {}
52 for tmp_title in top_articles:
53 if tmp_title == title:
54 article_edits_by_month[month][tmp_title] = 1
56 article_edits_by_month[month][tmp_title] = 0
59 # STEP 4: print it all out
60 # output the counts by month
61 output_file = open("hp_edits_by_month_top3_articles.tsv", "w", encoding='utf-8')
64 title_header_string = "\t".join(top_articles)
66 output_file.write("month\t" + title_header_string + "\n")
68 # iterate through every month and print out data into the file
69 for month in article_edits_by_month:
71 for title in top_articles:
72 title_values.append(str(article_edits_by_month[month][title]))
74 title_values_string = "\t".join(title_values)
75 output_file.write("\t".join([month, title_values_string]) + "\n")
79 # Example of interactive graph in Google Docs:
80 # http://mako.cc/go/0i