Python, TypeError: 'int' object does not support item assignment"

Python, TypeError: 'int' object does not support item assignment"

import numpy as np

def computeTF(wordDict, doc):
    tfDict ={}
    for word, count in wordDict.items():
        if count == 0:
            tfDict = 0
        else:
            tfDict[word] = 1 + np.log2(count)
    return tfDict

tfDoc1 = int(computeTF(wordDict1, doc1))

print (tfDoc1)

每当我尝试 运行 时,我都会收到错误消息:

'TypeError: 'int' object does not support item assignment'.

下面的代码可以工作,不会给你错误。您试图将 0 分配给字典对象,而不是将零添加到字典项。

import numpy as np

def computeTF(wordDict, doc):
    tfDict ={}
    for word, count in wordDict.items():
        if count == 0:
            tfDict[word] = 0 #this was wrong
        else:
            tfDict[word] = 1 + np.log2(count)
    return tfDict

tfDoc1 = int(computeTF(wordDict1, doc1))

print (tfDoc1)