【发布时间】:2015-10-06 12:27:45
【问题描述】:
我一直在尝试通过 Python 脚本运行 Twitter 用户名列表,该脚本从 Twitter 的 API 下载他们的推文历史记录。我将用户名作为 csv 文件,我尝试将其导入列表,然后使用 for 循环逐个通过脚本。但是,我收到此错误,因为它似乎一次将整个列表转储到脚本中:
<ipython-input-24-d7d2e882d84c> in get_all_tweets(screen_name)
60
61 #write the csv
---> 62 with open('%s_tweets.csv' % screen_name, 'wb') as f:
63 writer = csv.writer(f)
64 writer.writerow(["id","created_at","text"])
IOError: [Errno 36] File name too long: '0 TonyAbbottMHR\n1 AlboMP\n2 JohnAlexanderMP\n3 karenandrewsmp\n4
为简洁起见,我只是在代码中包含了一个列表,并将名称从 csv 导入到列表中被注释掉了。
抱歉,为了运行脚本,需要一个 Twitter API。我的代码如下:
#!/usr/bin/env python
# encoding: utf-8
import tweepy #https://github.com/tweepy/tweepy
import csv
import os
import pandas as pd
#Twitter API credentials
consumer_key = ""
consumer_secret = ""
access_key = ""
access_secret = ""
os.chdir('file/dir/path')
mps = [TonyAbbottMHR,AlboMP,JohnAlexanderMP,karenandrewsmp]
#df = pd.read_csv('twitMP.csv')
#for row in df:
#mps.append(df.AccName)
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_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
#initialize a list to hold all the tweepy Tweets
alltweets = []
#make initial request for most recent tweets (200 is the maximum allowed count)
new_tweets = api.user_timeline(screen_name = screen_name,count=200)
#save most recent tweets
alltweets.extend(new_tweets)
#save the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
#keep grabbing tweets until there are no tweets left to grab
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.user_timeline(screen_name = screen_name,count=200,max_id=oldest)
#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))
#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")] for tweet in alltweets]
#write the csv
with open('%s_tweets.csv' % screen_name, 'wb') as f:
writer = csv.writer(f)
writer.writerow(["id","created_at","text"])
writer.writerows(outtweets)
pass
if __name__ == '__main__':
#pass in the username of the account you want to download
for i in range(len(mps)):
get_all_tweets(mps[i])
【问题讨论】:
-
在将
screen_name传递给get_all_tweets函数之前,您肯定要打印它,以确保您正确运行它。 -
mps.append(df.AccName)应该做什么? -
Padraic:我想建立一个每个用户名的列表,以便从我在 csv 中的 Twitter 用户名列表中传递脚本。
标签: python csv for-loop twitter pandas