Created
August 15, 2012 06:59
-
-
Save stillinbeta/3357260 to your computer and use it in GitHub Desktop.
Get a list of all of your friend's mutual friends on facebook, then graph them.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import urllib.request | |
from urllib.error import URLError | |
import json | |
def get_json(url): | |
result_bytes = urllib.request.urlopen(url) | |
return json.loads(str(result_bytes.read(),'utf-8')) | |
MY_FID="1606470111" | |
ACCESS_TOKEN = "" | |
FRIENDS_URL = "https://graph.facebook.com/{user}/friends?access_token={access_token}" | |
MUTUAL_FRIENDS_URL= "https://graph.facebook.com/{me}/mutualfriends?user={user}&access_token={access_token}" | |
next_url = FRIENDS_URL.format(user="me", access_token=ACCESS_TOKEN) | |
friends = {} | |
while True: | |
results = get_json(next_url) | |
friends.update({obj['id']: {"name": obj['name']} for obj in results['data']}) | |
try: | |
next_url = results['paging']['next'] | |
except KeyError: | |
break | |
for fid in friends.keys(): | |
print(friends[fid]['name']) | |
try: | |
url = MUTUAL_FRIENDS_URL.format(me=MY_FID, user=fid, access_token=ACCESS_TOKEN) | |
friends_of_fid = get_json(url) | |
except URLError: | |
print("- failed") | |
continue | |
friends[fid]['friends'] = {obj['id']: obj['name'] | |
for obj in friends_of_fid['data']} | |
with open('friends-of-friends.json','w') as f: | |
json.dump(friends, f) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2 | |
import json | |
from math import ceil | |
import matplotlib.pyplot as plt | |
from matplotlib import mlab | |
JSON_FILE = "friends-of-friends.json" | |
BUCKET_INTERVAL = 5 | |
with open(JSON_FILE) as f: | |
fof = json.load(f) | |
mutualcount = [len(friend['friends']) for friend in fof.values()] | |
buckets = ceil(max(mutualcount) / float(BUCKET_INTERVAL)) | |
max_range = buckets * BUCKET_INTERVAL | |
n, bins, patches = plt.hist(mutualcount, bins=buckets, range=(0,max_range), cumulative=-1) | |
plt.plot(bins, linewidth=0) | |
plt.title("Histogram of Mutual Friends on Facebook") | |
plt.grid(True, axis='y') | |
plt.xlabel("At Least n Mutual Friends") | |
plt.ylabel("Number of Friends") | |
plt.show() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment