如何通过tweepy检索目前没有追随的追随者数量?

时间:2016-01-23 00:15:24

标签: python-2.7 twitter tweepy

我希望得到一些不在Twitter上关注我的帐户。我希望它看起来像这样:

(号码):目前没有追踪的帐户。

取消关注用户? 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()

1 个答案:

答案 0 :(得分:2)

您的notFollowing列表可以通过几种不同的方式创建。前两个只调用API两次;一次用于followers,一次用于friends。第三种方法应该用于检查"一次性"关系,因为每次你打电话,都会耗尽你的速度限制。

首先,使用列表理解的单行:

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)你耗尽时,你的一个限速,我想你每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()
    

    这可以为您节省很多速度限制的麻烦!