安裝 requests 和 facebook-sdk


In [ ]:
!pip install -U requests

In [ ]:
!pip install -U facebook-sdk

In [ ]:
token = raw_input()

In [ ]:
import facebook
import requests

In [ ]:
graph = facebook.GraphAPI(token, version="2.5")

設定一個工具函數,讀取所有分頁 data


In [ ]:
def get_all_data(graph, req, N=0):
    r = graph.get_object(req)
    rtn = []
    while N==0 or len(rtn)<N:
        rtn.extend(r['data'])
        if 'next' in r.get('paging', []):
            r=requests.get(r['paging']['next']).json()
        else:
            break
    return rtn

讀取自己的貼文,超過 100 篇就停止。


In [ ]:
posts = get_all_data(graph, 'me/posts', 100)
print len(posts)

從每篇貼文中找出 id, 和 likes 數,並且統計


In [ ]:
count = {}
for i, p in enumerate(posts):
    likes = get_all_data(graph, p['id']+"/likes")
    print i, p['id'], len(likes)
    for  x in likes:
        name = x['name']
        count[name]= count.get(name, 0)+1

找出按讚最多的朋友排序


In [ ]:
top_friends = sorted(count.items(), key=lambda x:-x[1])
for f in top_friends:
    print f[0], f[1]

In [ ]: