在Python/Django中显示朋友关注的Twitter粉丝

5 投票
1 回答
2071 浏览
提问于 2025-04-16 13:05

我正在开发一个应用的功能,目的是查看用户的关注者,并突出显示那些被用户的朋友(也就是用户关注的人)所关注的关注者。

我有两个问题:

  1. 有没有更有效的方法来实现这个功能?因为我需要检查每个用户朋友的朋友,这样可能会超过Twitter的API使用限制。

  2. 现在我创建的是一个包含朋友ID和他们关注的人的字典列表。其实,把字典改成关注者ID,然后列出关注他们的朋友会更好。有什么建议吗?

代码:

# Get followers and friends
followers = api.GetFollowerIDs()['ids']
friends = api.GetFriendIDs()['ids']

# Create list of followers user is not following
followers_not_friends = set(followers).difference(friends)

# Create list of which of user's followers are followed by which friends
followers_that_friends_follow = []
for f in friends:
    ff = api.GetFriendIDs(f)['ids']
    users = followers_not_friends.intersection(ff)
    followers_that_friends_follow.append({'friend': f, 'users': users })

1 个回答

1

关于你问题的第二部分:

import collections

followers_that_friends_follow = collections.defaultdict(list)
for f in friends:
    ff = api.GetFriendsIDs(f)['ids']
    users = followers_not_friends.intersection(ff)
    for user in users:
        followers_that_friends_follow[user].append(f)

这会生成一个字典,里面包含:

键(keys)= 用户的粉丝的ID,这些粉丝是用户不关注的,同时又是用户朋友关注的。

值(values)= 关注这些粉丝的朋友的ID列表,而这些朋友是用户不关注的。

举个例子,如果用户的一个粉丝的ID是23,而用户的两个朋友(用户16和用户28)关注了用户23,那么使用键23就会得到以下结果:

>>> followers_that_friends_follow[23]
[16,28]

撰写回答