TypeError:'NoneType'对象不是可迭代的问题。我如何设法绕过空语句?

问题描述 投票:1回答:3

我试图找到发送推文的位置,有些人显然没有在他们的推文上设置位置,所以我想知道如何绕过“TypeError:'NoneType'对象不可迭代”并显示“未识别” “回答它的位置?

我使用的代码是L`import json

with open('tweets7.txt')as json_data:
    data = json.load(json_data)
    for r in data['results']:
        for b in  r['place']:
        print (r['place']['full_name'])
        break
    print r['text']

`

python
3个回答
1
投票

在这种情况下你可以使用try / catch :)

with open('tweets7.txt')as json_data:
    data = json.load(json_data)
    for r in data['results']:
        try:
            for b in  r['place']:
                print (r['place']['full_name'])

        except TypeError:
            print("location not identified")

    print r['text']

0
投票

如果要检查可迭代对象是否存在,可以使用:

isinstance(data['results'], list)
isinstance(data.get('results', None), list)

如果您只想遍历数据['结果'],您可以使用:

for r in data.get('results', []):
    # Todo: your code
    pass

0
投票

如果您不能依赖输入来遵循您期望的格式,那么获得警告或至少比KeyErrorNoneType is not iterable更少的错误消息是有用的。

def get_tweets(filename):
    with open(filename) )as json_data:
        data = json.load(json_data)
    if 'results' not in data:
        raise ValueError("No 'results' in {0!r}".format(data))
    if data['results'] is None:
        return []
    for r in data['results']:
        if 'place' not in r:
           raise ValueError("No 'place' in {0!r}".format(r))
        if r['place'] is not None:
            for b in  r['place']:
                print('.… Oops, forgot to do anything with b')
            print (r['place']['full_name'])
            break
    if 'text' not in r:
        raise ValueError("No 'text' in {0!r}".format(r))
    print r['text']

get_tweets('tweets7.txt')

如果您不习惯编写健壮的代码,那么一开始可能看起来很陌生,以便在每个可能的机会上引发错误。这里的关键教训是提供有用的错误报告,以指出究竟是什么错误。您很快就会发现这显着提高了代码的可用性和可维护性;而不是一个奇怪的不起眼的NoneType追溯,或许距离发生实际问题的地方几十行,你会立即得到一个错误,这恰好表明某些事情不是你所期望的。

如果您认为您将能够在调用代码中处理其中的一些错误,请在每种情况下注意raise不同的错误,以便您可以确切地确定要实现的except处理程序。 (可能然后定义你自己的错误层次结构,就像我在这里使用Python的通用ValueError一样。)

© www.soinside.com 2019 - 2024. All rights reserved.