python 获取关注者子集中关注者的频率

83qze16e  于 2023-02-02  发布在  Python
关注(0)|答案(1)|浏览(120)

我正在用Tweepy创建一个python twitter机器人,在这个代码片段中我抓取了一个最近被关注的账户列表(每个twitter用户选中50个)。

while count < int(numOfIDs):
    print(twitterUsernameArray[count] + " follows these accounts:")
    response = client.get_users_following(id=twitterIDArray[count], max_results=50, user_fields=['username'])
    for user in response.data:
        followerArray.append(user.username)
    count += 1

followerArray.sort()
print(followerArray)

我希望能够打印出常用帐户。例如,假设人员A最近关注帐户1和2,人员B最近关注帐户2和3。我希望能够按以下方式打印出我最近关注的帐户列表:

2 followed by 2 accounts
1 followed by 1 account
3 followed by 1 account

谢谢你的帮助!

nkoocmlb

nkoocmlb1#

既然你想得到被关注账户的频率,你应该使用字典而不是列表。使用字典你可以用用户名设置键值,然后添加频率作为键值,这样做:

follower_dict = {}
while count < int(numOfIDs):
    print(twitterUsernameArray[count] + " follows these accounts:")
    response = client.get_users_following(id=twitterIDArray[count], max_results=50, user_fields=['username'])
    for user in response.data:
        if user.username in follwer_dict:
            follower_dict[user.username] += 1 # incrementing the count if the username is in the dictionary
        else:
            follower_dict[user.username] = 1 # adding an initial value to the dictionary as the username is not in the dictionary
    count += 1

print(follower_dict) # will print out the frequency dict like: {A: 1, B: 2, C: 1}

希望这是你要找的。

相关问题