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

Benjamin Mako Hill || Want to submit a patch?