38c299ded2ccd158e1cc6d04becd07d634ceb9d2
[harrypotter-wikipedia-cdsw] / build_hpwp_dataset.py
1 #!/usr/bin/env python
2 # coding=utf-8
3
4 import requests
5
6 # get_article_revisions is a function that takes an article title in
7 # wikipedia and return a list of all the revisions and metadata for
8 # that article
9 def get_article_revisions(title):
10     revisions = []
11
12     # create a base url for the api and then a normal url which is initially
13     # just a copy of it
14     # The following line is what the requests call is doing, basically.
15     # "http://en.wikipedia.org/w/api.php/?action=query&titles={0}&prop=revisions&rvprop=flags|timestamp|user|size|ids&rvlimit=500&format=json".format(title)
16     wp_api_url = "http://en.wikipedia.org/w/api.php/"
17
18     parameters = {'action' : 'query',
19                   'titles' : title,
20                   'prop' : 'revisions',
21                   'rvprop' : 'flags|timestamp|user|size|ids',
22                   'rvlimit' : 500,
23                   'format' : 'json',
24                   'continue' : '' }
25
26     # we'll repeat this forever (i.e., we'll only stop when we find
27     # the "break" command)
28     while True:
29         # the first line open the urls but also handles unicode urls
30         call = requests.get(wp_api_url, params=parameters)
31         api_answer = call.json()
32
33         # get the list of pages from the json object
34         pages = api_answer["query"]["pages"]
35
36         # for every page, (there should always be only one) get its revisions:
37         for page in pages.keys():
38             query_revisions = pages[page]["revisions"]
39
40             # for every revision, first we do some cleaning up
41             for rev in query_revisions:
42                 # let's continue/skip this revision if the user is hidden
43                 if "userhidden" in rev:
44                     continue
45                 
46                 # 1: add a title field for the article because we're going to mix them together
47                 rev["title"] = title
48
49                 # 2: let's "recode" anon so it's true or false instead of present/missing
50                 if "anon" in rev:
51                     rev["anon"] = True
52                 else:
53                     rev["anon"] = False
54
55                 # 3: let's recode "minor" in the same way
56                 if "minor" in rev:
57                     rev["minor"] = True
58                 else:
59                     rev["minor"] = False
60
61                 # we're going to change the timestamp to make it work a little better in excel/spreadsheets
62                 rev["timestamp"] = rev["timestamp"].replace("T", " ")
63                 rev["timestamp"] = rev["timestamp"].replace("Z", "")
64
65                 # finally, save the revisions we've seen to a varaible
66                 revisions.append(rev)
67
68         # 'continue' tells us there's more revisions to add
69         if 'continue' in api_answer:
70             # replace the 'continue' parameter with the contents of the
71             # api_answer dictionary.
72             parameters.update(api_answer['continue'])
73         else:
74             break
75
76     # return all the revisions for this page
77     return(revisions)
78
79 category = "Harry Potter"
80
81 # we'll use another api called catscan2 to grab a list of pages in
82 # categories and subcategories. it works like all the other apis we've
83 # studied!
84 #
85 # The following requests call basically does the same thing as this string:
86 # "http://tools.wmflabs.org/catscan2/catscan2.php?depth=10&categories={0}&doit=1&format=json".format(category)
87 url_catscan = "http://tools.wmflabs.org/catscan2/catscan2.php"
88
89 parameters = {'depth' : 10,
90               'categories' : category,
91               'format' : 'json',
92               'doit' : 1}
93
94 r = requests.get(url_catscan, params=parameters)
95 articles_json = r.json()
96 articles = articles_json["*"][0]["a"]["*"]
97
98 # open a file to write all the output
99 output = open("hp_wiki.tsv", "w", encoding="utf-8")
100 output.write("\t".join(["title", "user", "timestamp", "size", "anon", "minor", "revid"]) + "\n")
101
102 # for every article
103 for article in articles:
104
105     # first grab the article's title
106     title = article["a"]["title"]
107
108     # get the list of revisions from our function and then iterate through it,
109     # printing it to our output file
110     revisions = get_article_revisions(title)
111     for rev in revisions:
112         output.write("\t".join(['"' + rev["title"] + '"', '"' + rev["user"] + '"',
113                                rev["timestamp"], str(rev["size"]), str(rev["anon"]),
114                                str(rev["minor"]), str(rev["revid"])]) + "\n")
115
116 # close the file, we're done here!
117 output.close()
118     
119     

Benjamin Mako Hill || Want to submit a patch?