2013-11-26 32 views
0

時產生的錯誤是:Python的鍵錯誤

File "/home/tweet_v8/tweetSum/Summarizer/Sentence.py", line 42, in _tfIdfSentence 
    w.append(self.lsa.getCell(doc, self.vectorSpace.keywords()[(term,)]))  
KeyError: (u'l.a.',) 

的功能是這樣寫的:

# tf-idf computation for one sentence 
def _tfIdfSentence (self, sent, doc): 
    w = [] 
    for term in sent: 
     w.append(self.lsa.getCell(doc, self.vectorSpace.keywords()[(term,)]))  
    #print sent 
    if max(w) > 0: 
     #print [float(i)/max(w) for i in w], w, doc, sent 
     return [float(i)/max(w) for i in w] 
    else: 
     return [0] 

我不知道什麼是這行代碼的問題。

w.append(self.lsa.getCell(doc, self.vectorSpace.keywords()[(term,)]))  

有誰知道如何解決這個問題?

+2

我們不能幫你這個辦法。你試圖獲得的關鍵不存在,因爲我們不知道你的字典是什麼樣的,我不認爲這很容易幫助你。 – aIKid

+0

你試過這個嗎? 'w.append(self.lsa.getCell(doc,self.vectorSpace.keywords()[term]))' –

回答

0

您收到KeyError,因爲在self.vectorSpace.keywords()字典中找不到搜索的字典密鑰(u'l.a.',)

爲了避免KeyError,使用dictget()設置默認值,如果您正在尋找的關鍵不存在:

w.append(self.lsa.getCell(doc, self.vectorSpace.keywords().get((term,), 'default')) 

你會與你所需要的任何值替換'default'。另一種方法是使用defaultdict

0

KeyError: (u'l.a.',)

Python是告訴您鍵(鍵/值對用於字典)「L.A.」類型unicode不存在。

如果您只是想將它設置爲某些東西,您可以將其封裝在try/keyError中。

0

,你遇到的錯誤被稱爲KeyError是有原因的,並沒有一個可重複的代碼示例中,我們不能希望瞭解你在做什麼。但是,一個可以向你解釋什麼是KeyError

>>> d = {'a': 'happy'} 
>>> d['a'] 
'happy' 
>>> d['something_that_does_not_exist'] 
Traceback (most recent call last): 
    File "<console>", line 1, in <module> 
KeyError: 'something_that_does_not_exist' 

你看,你有什麼是字典,或俗稱哈希地圖。現在,當密鑰不存在於哈希映射中時,您會得到一個KeyError

0

很明顯,self.vectorSpace.keywords()返回一個字典。你期望這本詞典包含一定的價值 - 事實並非如此。或者它包含值 - 但是以非Unicode格式。 嘗試使用STR(項)代替長期 效率improvmenet的位:

kew_words = self.vectorSpace.keywords() 
for term in sent: 
    try: 
     w.append(self.lsa.getCell(doc, key_words[(str(term),)] 
    except KeyError: 
     <do some stuff> 

如果打印* key_words *它將幫助 - 檢查其內容