initial import of solutions for wikipedia data challenges
[wikipedia-cdsw-solutions] / solution_4.py
1 # 4. Which article is in more categories? Python (programming language) or R (programming language)? 
2
3 import requests
4
5 article_list = ["Python (programming language)", "R (programming language)"]
6  
7 for article in article_list:
8     # Get the list of categories
9     parameters = {'action' : 'query',
10                   'titles' : article,
11                   'prop' : 'categories',
12                   'format' : 'json',
13                   'continue' :  ''}
14
15     # reset the counter to zero once per article
16     counter = 0
17     
18     # run a "while True" loop
19     while True:
20         wp_call = requests.get('https://en.wikipedia.org/w/api.php', params=parameters)
21         response = wp_call.json()
22
23         for page_id in response["query"]["pages"].keys():
24             for category in response["query"]["pages"][page_id]['categories']:
25                 counter = counter + 1
26
27         if 'continue' in response:
28             parameters.update(response['continue'])
29         else:
30             break
31
32     output_line = "%s: %s categories" % (article, counter)
33     print(output_line)

Benjamin Mako Hill || Want to submit a patch?