我有以下功能:
def findTweetWith100PlusRTs():
global tweet_main
while tweet[tweet_main]["retweet_count"] < 100:
tweet_main += 1
它循环遍历列表中的推文,并找到转发次数超过 100 次的推文。
问题是,一段时间后,这种情况经常发生:
File "bot.py", line 41, in findTweetWith100PlusRTs
while tweet[tweet_main]["retweet_count"] < 100:
IndexError: list index out of range
这个错误破坏了脚本。
我怎样才能让我的脚本在发生这种情况时不停止,并运行一个函数来刷新列表以使其不会超出范围?
我想在 while 循环中使用这样的东西:
except IndexError:
time.sleep(120)
refreshTL()
如何在 while 循环中使用 except?
请您参考如下方法:
虽然您可以完成这项工作,但您应该使用 for 循环:
# this is a proper use of while! :-)
while True:
for current_tweet in tweet:
if current_tweet["retweet_count"] < 100:
# do something with current_tweet
pass
time.sleep(120)
refreshTL() # make sure you put a new list in `tweet[tweet_main]`
如果可以猜到,refreshTL() 添加了更多推文,您应该继续阅读 generators和迭代器,这是您想要使用的。
无限推文生成器的一个非常简单的示例是:
def tweets_generator():
tweets = None
while True:
# populate geneartor
tweets = fetch_tweets()
for tweet in tweets:
# give back one tweet
yield tweet
# out of tweets, go back to re-populate generator...
如果您实现 fetch_tweets,生成器会不断地重新填充推文。现在您可以执行以下操作:
# only take tweets that have less than 100 retweets thanks @Stuart
tg = (tweet for tweet tweet_generator() if tweet['retweet_count'] < 100)
for tweet in tg:
# do something with tweet
