如何解决如何忽略推文 ID statuses_lookup 中的 NoneType 错误
我正在尝试使用 good_tweet_ids_test
从推文 ID statuses_lookup
列表中收集带有 tweepy 的推文。
由于该列表有点旧,因此现在已经删除了一些推文。因此我忽略了 lookup_tweets 函数中的错误,所以它不会每次都停止。
这是我目前的代码:
def lookup_tweets(tweet_IDs,api):
full_tweets = []
tweet_count = len(tweet_IDs)
try:
for i in range((tweet_count // 100) + 1):
# Catch the last group if it is less than 100 tweets
end_loc = min((i + 1) * 100,tweet_count)
full_tweets.extend(
api.statuses_lookup(tweet_IDs[i * 100:end_loc],tweet_mode='extended')
)
return full_tweets
except:
pass
results = lookup_tweets(good_tweet_ids_test,api)
temp = json.dumps([status._json for status in results]) #create JSON
newdf = pd.read_json(temp,orient='records')
newdf.to_json('tweepy_tweets.json')
但是当我运行 temp = json.dumps([status._json for status in results])
行时,它给了我错误:
TypeError: 'nonetype' object is not iterable
我不知道如何解决这个问题。我相信一些状态的类型是无,因为它们已被删除,因此现在无法查找。如果类型为 None,我只是希望我的代码进入下一个状态。
编辑:正如已经指出的,问题是 results
是 None
。所以现在我想我需要从 None
变量中排除 full_tweets
值。但我不知道该怎么做。有什么帮助吗?
EDIT2:通过进一步的测试,我发现 results
只是 None
当有推文 ID 现在已在批处理中被删除时。如果批处理仅包含活动推文,则它有效。所以我想我需要弄清楚如何让我的函数查找一批推文,并且只返回那些不是 None
的推文。对此有什么帮助吗?
解决方法
当出现错误时,您可以显式返回一个空列表,而不是隐式返回 None
。这样,lookup_tweets
的结果将始终是可迭代的,并且调用代码将不必检查其结果:
def lookup_tweets(tweet_IDs,api):
full_tweets = []
tweet_count = len(tweet_IDs)
try:
for i in range((tweet_count // 100) + 1):
# Catch the last group if it is less than 100 tweets
end_loc = min((i + 1) * 100,tweet_count)
full_tweets.extend(
api.statuses_lookup(tweet_IDs[i * 100:end_loc],tweet_mode='extended')
)
return full_tweets
except:
return [] # Here!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。