我使用了朋友的这段代码,当我运行 heroku 时,它给了我以下错误:
Traceback (most recent call last):
File "ebooks.py", line 79, in <module>
source_tweets_iter, max_id = grab_tweets(api,max_id)
File "ebooks.py", line 51, in grab_tweets
max_id = user_tweets[len(user_tweets)-1].id-1
IndexError: list index out of range
嗯,我知道这个错误告诉了一些空列表(哪个列表?我不知道它意味着什么,所以请帮助我),有问题的行代码属于ebooks.py,那个&#39是的:
def grab_tweets(api, max_id=None):
source_tweets=[]
user_tweets = api.GetUserTimeline(
screen_name=user, count=200, max_id=max_id, include_rts=True,
trim_user=True, exclude_replies=True)
max_id = user_tweets[len(user_tweets)-1].id-1
for tweet in user_tweets:
tweet.text = filter_tweet(tweet)
if len(tweet.text) != 0:
source_tweets.append(tweet.text)
return source_tweets, max_id
您可以在此处找到原始的电子书:https://gist.github.com/laurenorsini/f38c0113e41e9b4504a7
好朋友,对不起我的英语:(你能帮助我吗?
答案 0 :(得分:2)
如果没有用户推文并且user_tweets
是空列表会怎么样?
然后,执行user_tweets[len(user_tweets) - 1]
相当于执行user_tweets[0 - 1]
user_tweets[-1]
。如果你my_list[-1]
,你告诉Python要查找列表中的最后一个元素。
但是,user_tweets
为空,则无法获取最后一个元素 - 列表中没有任何内容。所以,Python抛出异常。
我会尝试通过添加一项检查来修复您的代码,以确保user_tweets
不为空,并且可能会执行以下操作:
def grab_tweets(api, max_id=None):
user_tweets = api.GetUserTimeline(
screen_name=user, count=200, max_id=max_id, include_rts=True,
trim_user=True, exclude_replies=True)
if len(user_tweets) > 0:
source_tweets=[]
max_id = user_tweets[len(user_tweets)-1].id-1
for tweet in user_tweets:
tweet.text = filter_tweet(tweet)
if len(tweet.text) != 0:
source_tweets.append(tweet.text)
return source_tweets, max_id
else:
# return a default value?
# throw an exception?
答案 1 :(得分:0)
您在哪里设置用户?
要发现错误,请执行以下操作:
def grab_tweets(api, max_id=None):
source_tweets=[]
user_tweets = api.GetUserTimeline(
screen_name=user, count=200, max_id=max_id, include_rts=True,
trim_user=True, exclude_replies=True)
# if you're expecting it to succeed, use a try
try:
max_id = user_tweets[len(user_tweets)-1].id-1
# if user_tweets is empty an IndexError is raised
except IndexError:
# do any internal logging here before the return
return source_tweets, None
for tweet in user_tweets:
tweet.text = filter_tweet(tweet)
if len(tweet.text) != 0:
source_tweets.append(tweet.text)
return source_tweets, max_id
或者,如果您更喜欢使用if:
def grab_tweets(api, max_id=None):
source_tweets=[]
max_id = None
user_tweets = api.GetUserTimeline(
screen_name=user, count=200, max_id=max_id, include_rts=True,
trim_user=True, exclude_replies=True)
# you can use an if to prevent the error
if len(user_tweets):
max_id = user_tweets[len(user_tweets)-1].id-1
for tweet in user_tweets:
tweet.text = filter_tweet(tweet)
if len(tweet.text) != 0:
source_tweets.append(tweet.text)
return source_tweets, max_id
因此,这将捕获您的错误,但您仍然需要测试并确保它在您知道它应该返回填充列表时有效。检查用户设置是否正确,API是否正常工作等。