2014-08-29 24 views
-3

我有一本字典像這樣:如何從字典訪問字典中值的公式中使用

tfDic = { 
    '/home/seb/Learning/ex17output.txt': { 
     'COOL': 1, 
     'FILE': 1, 
     'FUN': 1, 
     'HAVE': 1, 
     'STUFF': 2 
    } 
} 

我試圖這樣做是爲了獲得「酷」的價值:

def tf(file, word): 
    return tfDic[file][word] 

,但我得到了一個KeyError。後來我想:

tf = tfDic[file].values()[term] 

,但我得到:

TypeError: list indices must be integers, not str 
+1

你首先應該選擇的作品,你能檢查你的文件名嗎 – levi 2014-08-29 13:57:02

+0

你是怎麼叫*'tf';你提供了什麼'file'和'word'的值?它對我來說很好(一旦錯字被修復)。第二個版本中的'values()'爲您提供了一個列表,例如'[1,2,1,1,1]',你不能用COOL'索引。 – jonrsharpe 2014-08-29 13:57:09

+0

@jonrsharpe我叫了循環TF使得該文件從列表中飼料和字被提供,即'TF(文件,「COOL」)'兩者應該是(而且)有,它是' COOL'引發錯誤,並且顯然存在 – Sebastian 2014-08-29 14:26:15

回答

0

如果你有一個KeyError,這意味着無論你fileword不匹配。打印出值,或在調試器中檢查它們。您的字典根本不包含您提供的值。

+0

該文件是從一個列表中提取的,所以它必須在那裏,KeyError跳出來,這個詞也是100% – Sebastian 2014-08-29 14:20:58

1

有趣,對我的作品。

>>> tfDic = { 
...  '/home/seb/Learning/ex17output.txt': { 
...   'COOL': 1, 
...   'FILE': 1, 
...   'FUN': 1, 
...   'HAVE': 1, 
...   'STUFF': 2 
...  } 
... } 
>>> def tf(file, word): 
...  return tfDic[file][word] 
... 
>>> 
>>> tf('/home/seb/Learning/ex17output.txt','COOL') 
1 
0

我只認識一個缺陷,並不是所有的子字典具有相同的話......

燁我是啞巴,TY試圖幫助