remove readme from the non-solutions
[twitter-api-cdsw-solutions] / solution-followers-7.py
1 # Make a "famous ratio" for a given user which I'll define as 'number
2 # of followers a person has divided by number of people they
3 # follow. Try out @makoshark, and @pontifex (the Pope). Who is higher?
4 #
5 #  This works for all users in my follower list.
6
7 import encoding_fix
8 import tweepy
9 from twitter_authentication import CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET
10
11 auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
12 auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
13
14 api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
15
16 user = api.get_user("makoshark")
17
18 # I found the list of functions in Tweepy here:
19 #   https://tweepy.readthedocs.org/en/v3.2.0/api.html
20
21 # I found the idea of how to the user the Cursor here:
22 #   https://tweepy.readthedocs.org/en/v3.2.0/cursor_tutorial.html
23
24 follower_ids = []
25 for page in tweepy.Cursor(api.followers_ids, screen_name="makoshark").pages():
26     for follower in page:
27         follower_ids.append(follower)
28
29
30 # the answer is using the api.lookup_users() code. unfortunately, this
31 # seems to only work with 100 users at a time. the following code makes that
32 # work
33 counter = 0
34 tmp_ids = []
35 users = []
36 for follower in follower_ids:
37     tmp_ids.append(follower)
38     counter = counter + 1
39
40     # if we've hit 100, we grab data and then reset things and keep going
41     if counter == 100:
42         tmp_users = api.lookup_users(user_ids=tmp_ids)
43         users = users + tmp_users
44
45         counter = 0
46         tmp_ids = []
47
48 # run once more when we're done
49 tmp_users = api.lookup_users(user_ids=tmp_ids)
50 users = users + tmp_users
51
52 # print out the famous ratios for users
53 famous_ratios = {}
54 for user in users:
55     famous_ratios[user.screen_name] = user.followers_count / user.friends_count
56
57 for user in sorted(famous_ratios, key=famous_ratios.get, reverse=True):
58     print(user, famous_ratios[user])
59

Benjamin Mako Hill || Want to submit a patch?