首页 > 解决方案 > 如何忽略推文 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

我不知道如何解决这个问题。我相信某些状态的类型是无,因为它们已被删除,因此现在无法查找。如果类型为无,我只是希望我的代码进入下一个状态。

编辑:正如已经指出的那样,问题resultsNone. 所以现在我想我需要Nonefull_tweets变量中排除值。但我不知道该怎么做。有什么帮助吗?

EDIT2:通过进一步测试,我发现results只有None当有一个推文 ID 现在已在批处理中删除时。如果该批次仅包含活动推文,则它可以工作。所以我想我需要弄清楚如何让我的函数查找这批推文,并且只返回那些不是None. 对此有什么帮助吗?

标签: jsonpython-3.xtweepy

解决方案


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!

推荐阅读