2016-04-22 9 views
0

私はTwitterのスクリーン名のリストを持っており、スクリーン名ごとに3200ツイートを集めたいと思っています。以下は、私が終わりhttps://gist.github.com/yanofsky/5436496Tweepyを使ってツイートを集めて保存する

#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ファイルはuser_cためUSER_A 3200人のつぶやき、User_Bへ約6400つぶやき、および9600件のつぶやきが含まれています。上記のコードで何かが間違っています。各ユーザーには約3200個のツイートが必要です。コード内で何が間違っているのか誰かが私に指摘できますか?ありがとう。

答えて

1

alltweetsに追加するために.extend()を使用しているため、forループが繰り返されるたびに、次のユーザーのつぶやきがすべて前のものに追加されています。おかげ

for i in r: 
    alltweets = [] 
    ... 
+0

が、これが唯一の最後の人(user_c)のつぶやきを保存します。ですから、各forループ反復の開始時にalltweetsをクリアしたいです。問題は残っています。 – kevin

+0

他の提案はありますか? – kevin

+0

ああ、ハハ。 3人のユーザー全員がつぶやくつぶやきを書いています。これは、forループの最後にある 'i'の値であるため、user_cから報告されているだけです。私は自分の答えを変えて、あなたのコードに必要な変更が少なくて済むようにします。 – mprat

関連する問題