“ ItemIterator”对象没有属性“ to_csv”

时间:2018-12-11 06:48:37

标签: python twitter

tweets = tweepy.Cursor(api.search, q=searchTerm).items(NoOfTerms)
tweets.to_csv("new.csv")

运行代码以从Twitter提取的推文中写入csv文件时,出现错误,

  

AttributeError跟踪(最近的调用)   最后)   ----> 1条tweets.to_csv(“ new.csv”)

     

AttributeError:“ ItemIterator”对象没有属性“ to_csv”

我该如何解决?谢谢

2 个答案:

答案 0 :(得分:1)

您对tweepy.Cursor(...).items()的调用返回一个迭代器。该迭代器没有方法to_csv()。相反,您要遍历Cursor对象的项目:

for tweet in tweepy.Cursor(api.search, q=searchTerm).items(NoOfTerms):
    # process tweet here
    process_tweet(tweet)

答案 1 :(得分:1)

这可以完成工作!

我建议您使用Python的csv。打开文件并在循环期间将其写入,如下所示:

#!/usr/bin/python
import tweepy
import csv #Import csv
auth = tweepy.auth.OAuthHandler('XXXXXX', 'XXXXXXX')
auth.set_access_token('XXX-XXX', 'XXX')

api = tweepy.API(auth)

# Open/create a file to append data to
csvFile = open('result.csv', 'a')

#Use csv writer
csvWriter = csv.writer(csvFile)

for tweet in tweepy.Cursor(api.search,
                           q = "google",
                           since = "2014-02-14",
                           until = "2014-02-15",
                           lang = "en").items():

    # Write a row to the CSV file. I use encode UTF-8
    csvWriter.writerow([tweet.created_at, tweet.text.encode('utf-8')])
    print tweet.created_at, tweet.text
csvFile.close()