如何检索当前未使用 tweepy 关注的关注者数量?

How to retrieve a count of followers not currently following back with tweepy?

我想在 Twitter 上恢复一些没有关注我的帐户。我希望它看起来像这样:

(number) : 当前未关注的帐户。

取消关注用户? y/n

取消关注 taylorswift13...等等

这是我目前拥有的:

followers = api.followers_ids(SCREEN_NAME)
friends = api.friends_ids(SCREEN_NAME)


notFollowing = friends not in followers
print (len(notFollowing), " : Accounts not following back")

def unfollowMain():
unfollowMain = raw_input("Unfollow users? y/n\n")
if unfollowMain == "y":
    for f in friends:
        if f not in followers:
            print "Unfollowing {0}".format(api.get_user(f).screen_name)
            api.destroy_friendship(f)
else:
    print("Exiting...")
    sys.exit()

unfollowMain()

您的 notFollowing 列表可以通过几种不同的方式创建。前两个只调用 API 两次;一次 followers,一次 friends。第三种方法应该用于检查"one-off"关系,因为每次调用它都会耗尽你的rate-limit.

首先,one-liner,使用列表理解:

notFollowing = [friend for friend in friends if friend not in followers]

其次,结果相同,但速度较慢:

notFollowing = []
for friend in friends:
    if friend not in followers:
        notFollowing.append(friend)

第三个是调用API方法api.exists_friendship(user_a,user_b)

关于unfollowMain()函数的一些建议:

  1. 最初您不必要地使用嵌套 for 循环来检查友谊状态。现在您已经创建了 notFollowing,只需循环一次,然后取消关注每一个。

  2. 每次执行此操作时 api.get_user(f).screen_name) 你会筋疲力尽,你的 rate-limit 之一,我想你每 15 分钟就会得到 180。所以如果你想象你的 len(notFollowing) > 180 那么你的程序将因错误而崩溃。出于这个原因,最好使用 tweepy Cursor.

  3. 进行批处理

示例代码:

followers = api.followers_ids(SCREEN_NAME)  # still only need your followers ids

friends = []
for friend in tweepy.Cursor(api.friends, user_id=SCREEN_NAME).items():  
    friends.append(friend)  # friend is now a User object, print one to see what's in it.

notFollowing = [friend for friend in friends if friend.id not in followers] # note friend.id
print (len(notFollowing), " : Accounts not following back")

def unfollowMain():
    unfollowMain = raw_input("Unfollow users? y/n\n")
    if unfollowMain == "y":
        for f in notFollowing: # now f is a User obejct from above
            print "Unfollowing {0}".format(f.screen_name) # now you can access the User's screen_name
            api.destroy_friendship(f.id)
        else:
            print("Exiting...")
            sys.exit()

unfollowMain()

这应该会为您省去很多令人头疼的速率限制问题!