如何解决从用户的时间轴提取推文的功能是循环
当我运行该功能时,该功能会带回约200条推文,然后循环播放,直到达到用户实际拥有的推文总数为止。因此它将重复200条推文,直到达到该数目为止。
def extract_tweets(userid):
tweets = api.user_timeline(screen_name = userid,count = 200,include_rts = True,tweet_mode = 'extended')
for info in tweets[:3]:
print('ID: {}'.format(info.id))
print(info.created_at)
print(info.full_text)
print('\n')
all_tweets = []
all_tweets.extend(tweets)
oldest_id = tweets[-1].id
tweet_num = api.get_user(userid).statuses_count
while len(all_tweets) < tweet_num:
tweets = api.user_timeline(screen_name = userid,tweet_mode = 'extended')
if len(tweets) == 1000:
break
oldest_id = tweets[-1].id
all_tweets.extend(tweets)
outtweets = [[tweet.id_str,tweet.created_at,tweet.favorite_count,tweet.retweet_count,tweet.full_text.encode('utf-8').decode('utf-8')]
for idx,tweet in enumerate(all_tweets)]
df = DataFrame(outtweets,columns =['id','created_at','favorite_count','retweet_count','text'])
df.to_csv('%s_tweets.csv' % userid,index = False)
df.head(3)
解决方法
您的中断条件(len(tweets)== 1000)永远不会为真,因为返回的最大tweets数量为200。如果要在收集所有用户tweet时退出循环,则中断条件应为:
if len(tweets) == 0:
break
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。