python - 随机 "int is not subscriptable"行为

标签 python json exception dictionary casting

我正在读取一个有效的 JSON 文件(嵌套 5 层),然后向其中添加一些数据,然后尝试使用该数据进行一些计算。

我得到 int is not subscriptable以随机方式出现错误。我无法理解它。转换到str()没有帮助,使用 pprint 打印并没有减轻它,转换到 int()输入也无济于事。我绝望地用尽了选择...

主要功能

with open(rNgram_file, 'r', encoding='utf-8') as ngram_file:
    data = json.load(ngram_file)
    data = rank_items(data)
    data = probability_items(data)

rank_items(数据)

所有值都在 5 层嵌套级别计算,并在树中向上添加。我添加了 int()转换为输入作为可能的解决方案,但这没有帮助。 获取 x_grams['_rank'] 时出现问题

for ngram, one_grams in data.items():
        ngram_rank = 0
        for one_gram, two_grams in one_grams.items():
            one_gram_rank = 0
           [..]
                for four_gram, values in four_grams.items():
                # 4gram = of, values = 34
                three_gram_rank += values
                four_grams['_rank'] = int(three_gram_rank)
                two_gram_rank += three_gram_rank
           [..]    
            two_grams['_rank'] = int(one_gram_rank)
            ngram_rank += one_gram_rank
        one_grams['_rank'] = int(ngram_rank)

probability_items(数据)

这是错误发生的地方。看似随意,它会提示int is not subscriptable其中 x_rankx_grams['rank]正在打印或分配,即使它们是用 type() 评估的(如果有效,则表示 <class 'int'> ) 我在下面用注释标记了最常见的行。 奇怪的是,第 2 行和第 3 行从未引发异常...

    for ngram, one_grams in data.items():
        ngram_rank = int(one_grams['_rank'])               # never gives an error
        print("NgramRank: ", str(ngram_rank))              # never gives an error
        if ngram != '_rank':
            for one_gram, two_grams in one_grams.items():
                pprint(type(two_grams['_rank']))             # common error point
                one_gram_rank = str(two_grams['_rank'])      # never reaches this
                if one_gram != '_rank':
                    for two_gram, three_grams in two_grams.items():
                        pprint(type(three_grams['_rank']))   # common error point
                        pprint(str(three_grams['_rank']))    # never reaches this
                        two_gram_rank = str(three_grams['_rank'])
                        [..]
                    one_gram_prob = int(one_gram_rank) / int(ngram_rank)
                    two_grams['_prob'] = one_gram_prob
            ngram_prob = int(ngram_rank) / int(ngram_rank)
            one_grams['_prob'] = ngram_prob

以随机方式,在上面的常见错误点上抛出异常。由于这些异常,永远不会达到下面的行。但是如果你删除了常见的错误点,下面的几行就变成了错误点。 有时,它会在内部 for 循环中完全运行,打印 <class 'int'>评估时,以及所有,直到它因异常而停止。

我不知道发生了什么,我什至不明白当我用 Type() 评估它时这个错误是如何发生的

由于这是一个奇怪的问题,而且我显然犯了一个奇怪的错误,所以我将所有代码放在此处的要点中:https://gist.github.com/puredevotion/7922480

希望有人能帮忙!

追溯细节

['Traceback (most recent call last):\n', '  File "Ngram_ranking.py", line 121, in probability_items\n    pprint(type(four_grams[\'_rank\']))\n', "TypeError: 'int' object is not subscriptable\n"]

*** extract_tb:
[('Ngram_ranking.py', 121, 'probability_items', "pprint(type(four_grams['_rank']))")]

*** format_tb:
['  File "Ngram_ranking.py", line 121, in probability_items\n    pprint(type(four_grams[\'_rank\']))\n']

*** tb_lineno: 121
Exception in on line 121: pprint(type(four_grams['_rank'])): 'int' object is not subscriptable

第 115 行的回溯

['Traceback (most recent call last):\n', '  File "Ngram_ranking.py", line 115, in probability_items\n    pprint(type(three_grams[\'_rank\']))\n', "TypeError: 'int' object is not subscriptable\n"]

*** extract_tb:
[('Ngram_ranking.py', 115, 'probability_items', "pprint(type(three_grams['_rank']))")]

*** format_tb:
['  File "Ngram_ranking.py", line 115, in probability_items\n    pprint(type(three_grams[\'_rank\']))\n']

*** tb_lineno: 115
Exception in on line 115: pprint(type(three_grams['_rank'])): 'int' object is not subscriptable

probability_items(data) 顶部的 PPRINT(data)

{'aesthetic': {'_rank': 290,
           'feeling': {'_rank': 10,
                       'the': {'_rank': 10,
                               'feeling': {'_rank': 10, 'of': 10}}},
           'perception': {'_rank': 280,
                          'and': {'_rank': 190,
                                  'the': {'_rank': 190,
                                          'design': 15,
                                          'environment': 5,
                                          'music': 100,
                                          'painting': 15,
                                          'work': 5,
                                          'works': 50}},
                          'of': {'_rank': 90,
                                 'the': {'_rank': 50,
                                         'work': 30,
                                         'world': 20},
                                 'their': {'_rank': 40, 'female': 40}}}}}

最佳答案

问题是您有一个多层嵌套字典,尽管嵌套有些不同,但您为所有三个级别复制了相同的代码。

我只是拿你字典的一部分

{
'aesthetic': 
    {
    '_rank': 290,
    'feeling': 
        {
        '_rank': 10,
        'the': 
            {
            '_rank': 10,
            'feeling': 
                {
                '_rank': 10, 
                'of': 10
                }
            }
         },
    }
}

您的顶级字典是统一的,因为值(对于键 aesthetic)始终是字典。但是较低级别也有 int 作为它们的一些值。

因此当你这样做的时候

for ngram, one_grams in data.items():

你有 ngram=aestheticsone_grams={the dictionary}

int(one_grams['_rank'])

将始终有效(因为值字典具有元素 _rank。因此您永远不会在此处遇到错误。

现在我们进入下一步

one_gram, two_grams in one_grams.items()

one_grams 字典运行 .items() 给出

(one_gram,two_grams) = [('_rank', 290), ('feeling', {'_rank': 10, 'the': {'_rank': 10, 'feeling': {'_rank': 10, 'of': 10}}})]

注意 two_grams 是第一个条目的 int 和第二个条目的 dict。因为你在做的时候遍历了整个 items()

two_grams['_rank']

您遇到了错误(它告诉您在预期 dict 时遇到了 int)。同样的问题发生在内部循环中。

由于字典没有排序,items() 可以按任何顺序返回。因此 _rank 可能是第一个元素或低于其他字典元素。在这种情况下,您会进入内部 for 循环并在那里遇到相同的问题。

您可以在迭代时忽略 _rank

for one_gram,two_grams one_grams.items(): 
    if one_gram=='_rank': 
        continue  

在所有循环中。

关于python - 随机 "int is not subscriptable"行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20534107/

相关文章:

android - 如何更新Android应用程序中的最新通知?

java - 使用 JsonPath 在不知道键的情况下提取值

python - 尝试删除 Pandas 中的异常值时出现 ValueError

python - 验证 Tensorflow 流中是否存在该文件。使用 tf.gfile.Exists 以字符串张量作为输入

python - 嵌入 Python Zip 文件会抛出错误?

python - 使用元组而不是 bool 运算符

vb.net - 如何将 Handsontable 保存到数据库

exception - Lua - "attempt to compare number with nil"错误

c# - 下载文件引发异常

java - 无法找到我的 Java 纸牌游戏的 hasNext() 和 next() 方法的符号