我正在尝试从包含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
答案 0 :(得分:6)
事实上,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)