改进代码,使用twitter API查找追随者的追随者

2024-04-27 20:22:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要这方面的帮助:

我已经用python创建了这段代码,但我没有找到改进它并缩短它的方法,因为有一些步骤需要重复。这就是我目前得到的。我试图做的是首先获得早期采用者列表的追随者,然后获得追随者的追随者,然后再做三次相同的步骤

early_adopters = ['user_ID_1', 'user_ID_2']

users_follower = [] # list of every followers from early adopters 
follower_list = [] # list of pairs of users (early_apdoter, follower)

for usr in early_adopters:
  for user in tweepy.Cursor(api.followers, user_id = usr).items(3):
    if user.id not in early_adopters:
      users_follower.append(user.id_str)
      follower_list.append((usr,user.id_str))


users_follower_S1 = random.choices(users_follower, k=3) # sample of user from the first surface follower_list_search
follower_list_1 = []  #list of pair of followers of followers 
s2_follower_list = [] # list of pairs of users (early_apdoter, follower) 

for usr_s1 in users_follower_S1:
  for user in tweepy.Cursor(api.followers, user_id = usr_s1).items(3):
    if user.id_str not in follower_list and usr_s1 not in early_adopters:
      follower_list_1.append(user.id_str)
      s2_follower_list.append((usr_s1, user.id_str))


users_follower_S2 = random.choices(follower_list_1, k=3) # Repeat the same process above but for the second surface 
follower_list_2 = []
s3_follower_list = [] 

for usr_s2 in users_follower_S2:
  for user in tweepy.Cursor(api.followers, user_id = usr_s2).items(3):
    if user.id_str not in follower_list and usr_s2 not in early_adopters:
      follower_list_2.append(user.id_str)
      s3_follower_list.append((usr_s2, user.id_str))


users_follower_S3 = random.choices(follower_list_2, k=3) # Repeat the same process above but for the second surface 
follower_list_3 = []
s4_follower_list = [] 

for usr_s3 in users_follower_S3:
  for user in tweepy.Cursor(api.followers, user_id = usr_s3).items(3):
    if user.id_str not in follower_list and usr_s3 not in early_adopters:
      follower_list_3.append(user.id_str)
      s4_follower_list.append((usr_s3, user.id_str))

提前谢谢


Tags: ofinidforusrnotuserslist
1条回答
网友
1楼 · 发布于 2024-04-27 20:22:30

可能将重复代码包装在函数中,例如:

def getFollowers(users)
    followers = []
    follower_pairs = []

    for usr in users:
      for user in tweepy.Cursor(api.followers, user_id = usr).items(3):
        if user.id not in users and user.id not in early_adopters:
          followers.append(user.id_str)
          follower_pairs.append((usr,user.id_str))

    return (followers, follower_pairs)

示例用例:

early_adopters = ['user_ID_1', 'user_ID_2']

users_follower, follower_list = getFollowers(early_adopters)

我可能在你的逻辑中遗漏了一些东西,但这是我的总体建议

相关问题 更多 >