Tweepy 使用 user_id(Python 脚本)从文本文件中关注 Twitter 用户

Tweepy follow Twitter users from text file using user_id (Python script)

我正在尝试从一个包含 27 个 user_ids 的文本文件中跟踪 user_ids - 每行一个,例如:

217275660
234874181
27213931
230766319
83695362
234154065
68385750

我有一些代码似乎可以工作,除了它说 user_id 未定义(请参阅底部粘贴的错误)...但是 user_id 应该是 Tweepy 中的正确变量。 .. 之后有或没有 [follow]。我的代码如下:

# Script to follow Twitter users from text file containing user IDs (one per line)

# Header stuff I've just thrown in from another script to authenticate

import json
import time
import tweepy
import pprint
from tweepy.parsers import RawParser
from auth import TwitterAuth
from datetime import datetime

auth = tweepy.OAuthHandler(TwitterAuth.consumer_key, TwitterAuth.consumer_secret)

auth.set_access_token(TwitterAuth.access_token, TwitterAuth.access_token_secret)

rawParser = RawParser()

api = tweepy.API(auth_handler = auth, parser = rawParser)

# Open to_follow.txt

to_follow = [line.strip() for line in open('to_follow.txt')]
print to_follow

# Follow everyone from list?!

for user_id in to_follow:
    try:
        api.create_friendship(user_id)
    except tweepy.TweepError as e:
        print e
        continue

print "Done."

错误是:

$ python follow.py
['217275660', '234874181', '27213931', '230766319', '83695362', '234154065', '68385750', '94981006', '215003131', '30921943', '234526708', '229259895', '88973663', '108144701', '233419650', '70622223', '95445695', '21756719', '229243314', '18162009', '224705840', '49731754', '19352387', '80815034', '17493612', '23825654', '102493081']
Traceback (most recent call last):
  File "follow.py", line 30, in <module>
    api.create_friendship(user_id)
NameError: name 'user_id' is not defined

确实 user_id 没有在您的代码中的任何地方定义。

我想你的意思是:
for user_id in to_follow:

user_id 个在列表中

附带说明 - 下面的代码更好更正统:

with open('to_follow.txt') as f:
    for line in f:
        user_id = line.strip()
        api.create_friendship(user_id)