json - 如何忽略推文 ID statuses_lookup 中的 NoneType 错误
问题描述
我正在尝试从推文 ID 列表中收集带有 tweepy 的推文good_tweet_ids_test
,使用statuses_lookup
. 由于列表有点旧,一些推文现在将被删除。因此,我忽略了 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
我不知道如何解决这个问题。我相信某些状态的类型是无,因为它们已被删除,因此现在无法查找。如果类型为无,我只是希望我的代码进入下一个状态。
编辑:正如已经指出的那样,问题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!
推荐阅读
- firebase - 我应该为我的应用程序使用哪个支付网关(flutter 开发)?我目前正在使用 Firebase 作为后端,并使用颤振进行编码
- arduino - 如何通过只按一次来存储按钮值
- flutter - 使用 StreamProvider 的颤振提供者 MultiProvider
- django - 如何包含 React 到 django 的路线?
- python - 如何使用多处理 RLock 和 Pool 写入同一个文件
- xcode - 如何更改已完成 Xcode 项目的签名
- php - 使用 PDO、AJAX 进行分页
- bash - Hashicorp 使用 Azure 保管库自动解封
- google-data-studio - Cloud MySQL DATETIME 列的时间序列图表中没有显示数据
- javascript - 循环并显示对象内的内容