2015-11-14 51 views
-1
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) 

每當我嘗試運行此,我得到一個錯誤:Python中,類型錯誤:「詮釋」對象不支持項目分配」

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

+3

我不是匈牙利符號風格的命名約定的粉絲,但肯定'tfDict = 0'應該提出一面紅旗?! – jonrsharpe

回答

0

下面的代碼將工作,不會給你錯誤了。你想分配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) 
相關問題