Python 试图收集过去24小时的所有推文,并将其放入CSV文件中
我正试图收集过去24小时的所有推文,并将它们放入CSV文件中 当我这样做的时候,我会Python 试图收集过去24小时的所有推文,并将其放入CSV文件中,python,csv,twitter,tweepy,Python,Csv,Twitter,Tweepy,我正试图收集过去24小时的所有推文,并将它们放入CSV文件中 当我这样做的时候,我会 _csv.Error: iterable expected, not datetime.datetime 作为错误 有人能告诉我如何消除这个错误以及可能对代码进行的任何其他改进吗 def get_all_tweets(screen_name): # Twitter only allows access to a users most recent 3240 tweets with this method #
_csv.Error: iterable expected, not datetime.datetime
作为错误
有人能告诉我如何消除这个错误以及可能对代码进行的任何其他改进吗
def get_all_tweets(screen_name):
# Twitter only allows access to a users most recent 3240 tweets with this method
# authorize twitter, initialize tweepy
auth = tweepy.OAuthHandler(consumer_token, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)
# initialize a list to hold all the tweepy Tweets
alltweets = []
# make initial request for most recent tweets (20 is the maximum allowed count)
new_tweets = api.home_timeline (screen_name=screen_name, count=20)
# save most recent tweets
alltweets.extend(new_tweets)
# save the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
page = 1
deadend = False
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.home_timeline(screen_name=screen_name, count=20, max_id=oldest, page = page)
# 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)))
for tweet in alltweets:
if (datetime.datetime.now() - tweet.created_at).days < 1:
# transform the tweepy tweets into a 2D array that will populate the csv
outtweets = [tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")]
else:
deadend = True
return
if not deadend:
page += 1
time.sleep(10)
# write the csv
with open('%s_tweetsBQ.csv' % screen_name, 'w') as f:
writer = csv.writer(f)
writer.writerow(["id", "created_at", "text"])
writer.writerows(outtweets)
pass
print ("CSV written")
if __name__ == '__main__':
# pass in the username of the account you want to download
get_all_tweets("BQ")
outtweets
只包含一行数据writer.writerows()
需要一个行列表,即列表列表:
[
[columns, in, row, 1],
[columns, in, row, 2],
]
您正在设置outtweets
,如下所示:
outtweets = [tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")]
那只是一排。要将此信息传递给
writerows
,您需要将每行数据累积到一个列表中,然后将该列表传递给writerows
请修复缩进并发布回溯的全文。缩进已修复,将回溯添加到问题中使用该函数执行我要求的操作。不要在评论中发布代码或回溯,它们是无法阅读的。对不起,这是我第一次在这里添加它们。我不知道,我现在把它们放到了问题中。谢谢,我对这一点完全陌生,你能告诉我如何将行放入列表中吗?如果你有一个列表,你可以使用append
方法将一些东西添加到列表中。如mylist=[];mylist.append(一些值)
。甚至我的列表。附加(一些其他列表)
。希望这能为您指明正确的方向。那么我应该在循环之前创建一个列表实例,然后在循环的每次迭代中追加?
[
[columns, in, row, 1],
[columns, in, row, 2],
]
outtweets = [tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")]