24.07.2016 Views

www.allitebooks.com

Learning%20Data%20Mining%20with%20Python

Learning%20Data%20Mining%20with%20Python

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Discovering Accounts to Follow Using Graph Mining<br />

We <strong>com</strong>plete our function by returning the friends we collected:<br />

return friends<br />

The full function is given as follows:<br />

import time<br />

def get_friends(t, user_id):<br />

friends = []<br />

cursor = -1<br />

while cursor != 0:<br />

try:<br />

results = t.friends.ids(user_id= user_id,<br />

cursor=cursor, count=5000)<br />

friends.extend([friend for friend in<br />

results['ids']])<br />

cursor = results['next_cursor']<br />

if len(friends) >= 10000:<br />

break<br />

except TypeError as e:<br />

if results is None:<br />

print("You probably reached your API limit,<br />

waiting for 5 minutes")<br />

sys.stdout.flush()<br />

time.sleep(5*60) # 5 minute wait<br />

else:<br />

raise e<br />

except twitter.TwitterHTTPError as e:<br />

break<br />

finally:<br />

time.sleep(60)<br />

return friends<br />

Building the network<br />

Now we are going to build our network. Starting with our original users, we will get<br />

the friends for each of them and store them in a dictionary (after obtaining the user's<br />

ID from our user_id dictionary):<br />

friends = {}<br />

for screen_name in relevant_users:<br />

user_id = user_ids[screen_name]<br />

friends[user_id] = get_friends(t, user_id)<br />

[ 142 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!