2016-08-02 75 views
0

在Python 2.7中使用Tweepy將搜索查詢結果存儲到CSV文件中。我想知道如何從結果集中打印唯一的tweet.id數量。我知道(len(list))有效,但顯然我沒有在這裏初始化一個列表。我是python編程的新手,所以解決方案可能很明顯。任何幫助表示讚賞。Python打印不同值

for tweet in tweepy.Cursor(api.search, 
       q="Wookie", 
       #since="2014-02-14", 
       #until="2014-02-15", 
       lang="en").items(5000000): 
    #Write a row to the csv file 
    csvWriter.writerow([tweet.created_at, tweet.text.encode('utf-8'), tweet.favorite_count, tweet.user.name, tweet.id]) 
    print "...%s tweets downloaded so far" % (len(tweet.id)) 
csvFile.close() 

回答

2

你可以使用一個set保持到目前爲止你見過的唯一ID的曲目,然後打印:

ids = set() 
for tweet in tweepy.Cursor(api.search, 
       q="Wookie", 
       #since="2014-02-14", 
       #until="2014-02-15", 
       lang="en").items(5000000): 
    #Write a row to the csv file 
    csvWriter.writerow([tweet.created_at, tweet.text.encode('utf-8'), tweet.favorite_count, tweet.user.name, tweet.id]) 
    ids.add(tweet.id) # add new id 
    print "number of unique ids seen so far: {}".format(len(ids)) 
csvFile.close() 

集是像列表一樣,不同的是它們只保留獨特的元素。它不會將重複項添加到集合中。

+0

得到一個錯誤,如.. 類型錯誤:類型的「長」對象沒有LEN() – hansolo

+0

想通了,這是我 '打印「...%s的鳴叫下載到目前爲止」%(LEN( tweet.id))' 這是拋出錯誤。我刪除了,計數工作。再次感謝@xgord – hansolo

+0

@hansolo良好的捕獲,我沒有注意到,當我包括你的代碼示例。我現在已經刪除了該行。 – xgord