我有一个Twitter昵称的列表,我想收集每个昵称3200条tweets。下面是我改编自https://gist.github.com/yanofsky/5436496的代码
#initialize a list to hold all the tweepy Tweets
alltweets = []
#screen names
r=['user_a', 'user_b', 'user_c']
#saving tweets
writefile=open("tweets.csv", "wb")
w=csv.writer(writefile)
for i in r:
#make initial request for most recent tweets (200 is the maximum allowed count)
new_tweets = api.user_timeline(screen_name = i, count=200)
#save most recent tweets
alltweets.extend(new_tweets)
#save the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
#keep grabbing tweets until there are no tweets left to grab
while len(new_tweets) > 0:
print "getting tweets before %s" % (oldest)
#all subsiquent requests use the max_id param to prevent duplicates
new_tweets = api.user_timeline(screen_name = i[0],count=200,max_id=oldest)
#save most recent tweets
alltweets.extend(new_tweets)
#update the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
print "...%s tweets downloaded so far" % (len(alltweets))
#write the csv
for tweet in alltweets:
w.writerow([i, tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")])
writefile.close()
最后,最后的csv文件包含3200条推文给用户_a,约6400条tweets给用户_b,9600条tweets给用户_c,上面的代码有些不正确。每个用户应该有3200条推文。有人能告诉我密码有什么问题吗?谢谢。在
因为您使用
.extend()
添加到alltweets
,所以for
循环的每次迭代都会导致下一个用户的所有tweet都被添加到前一个tweet中。因此,您希望在每个for
循环迭代开始时清除alltweets
:相关问题 更多 >
编程相关推荐