Python打印不同的值

2024-04-24 02:42:48 发布

您现在位置:Python中文网/ 问答频道 /正文

在python2.7中使用Tweepy将搜索查询的结果存储到CSV文件中。我在想我怎么才能只打印出推特.ids从我的结果集中。我知道(len(list))是有效的,但显然我还没有在这里初始化列表。我是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()

Tags: 文件csvinidids列表forlen
1条回答
网友
1楼 · 发布于 2024-04-24 02:42:48

您可以使用^{}跟踪到目前为止看到的唯一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()

集合类似于列表,只是它们只保留唯一的元素。它不会向集合中添加重复项。你知道吗

相关问题 更多 >