通过 Python 中的另一个程序将列表中的名称循环到 运行

Looping through names on a list to run through another program in Python

我一直在尝试 运行 通过 Python 脚本从 Twitter API 下载他们的推文历史记录的 Twitter 用户名列表。我将用户名作为 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])

好像是这个

#df = pd.read_csv('twitMP.csv')

#for row in df:
    #mps.append(df.AccName) 

您的部分代码给您带来了麻烦。

这是您遇到的问题

问题 1

当迭代 DataFrame 对象时,您实际上会迭代它的列名,因此您不想这样做。您可以通过 运行 list(df) 其中 returns 列名列表来查看。

问题 2

当您附加 df.AccName 时,您实际上是在附加整个列。所以最后,mps 变成了一个包含 DataFrame 列的列表,每个元素都相同且等于 df.AccName

解决方案

您只需

df = pd.read_csv('twitMP.csv')
mps = df.AccName.tolist() #or df.AccName.astype(str).tolist() if they aren't strings, but they should be

奖金

当你遍历 mps 时,尝试使用 enumerate,你得到两个变量,我认为代码更清晰

for i,name in enumerate( mps):
    get_all_tweets( name ) 

您仍然可以在每次迭代中随心所欲地使用 name (i) 的索引,.