2016-08-02 57 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