1
+ from __future__ import print_function
2
+ import json
3
+
4
+ try :
5
+ # Python 3
6
+ from urllib .request import urlopen , Request
7
+ except ImportError :
8
+ # Python 2
9
+ from urllib2 import urlopen , Request
10
+
11
+ # https://www.anapioficeandfire.com/Documentation
12
+
13
+ headers = {'User-Agent' : 'Mozilla/5.0' }
14
+
15
+ endpoints = {
16
+ 'characters' : 'https://www.anapioficeandfire.com/api/characters/?page=%d&pageSize=%d' ,
17
+ 'houses' : 'https://www.anapioficeandfire.com/api/houses/' ,
18
+ 'books' : 'https://www.anapioficeandfire.com/api/books/'
19
+ }
20
+
21
+ pages = 20
22
+ num_characters = 50
23
+ all_characters = []
24
+
25
+ for page in range (1 , pages + 1 ):
26
+
27
+ url = endpoints ['characters' ] % (page , num_characters )
28
+
29
+ request = Request (url , headers = headers )
30
+ response = urlopen (request )
31
+ contents = response .read ()
32
+
33
+ characters = json .loads (contents )
34
+
35
+ print ("Collected characters from page %d" % page )
36
+
37
+ all_characters .extend (characters )
38
+
39
+ print ("The total number of characters is %d" % len (all_characters ))
40
+
41
+ # Filtering using a list comprehension
42
+ dead_char = [ch ['name' ] for ch in all_characters if ch ['died' ] != '' ]
43
+
44
+ # Filtering using a higher order function
45
+ def is_dead (character ):
46
+ if character ['died' ] != "" :
47
+ return True
48
+ return False
49
+
50
+ dead_char = list (filter (is_dead , all_characters ))
51
+
52
+ print ("The number of dead characters is %d" % len (dead_char ))
53
+ print ("The number of alive characters is %d" % (len (all_characters ) - len (dead_char )))
54
+
55
+ # print("The URL for characters is %s" % endpoints['characters'])
56
+ # print("The URL for books is %s" % endpoints['books'])
57
+ # print("The URL for houses is %s" % endpoints['houses'])
58
+
0 commit comments