joe*_*ep1 3 python twitter tweepy
我试图从具有27个user_ids的文本文件中关注user_ids - 每行一个,例如:
217275660
234874181
27213931
230766319
83695362
234154065
68385750
Run Code Online (Sandbox Code Playgroud)
我有一些似乎有效的代码,除了它说没有定义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."
Run Code Online (Sandbox Code Playgroud)
错误是:
$ 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
Run Code Online (Sandbox Code Playgroud)
实际上,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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3570 次 |
| 最近记录: |