2014-08-28 63 views
0

我一直試圖在Python中使用gensim使用word2vec。雖然我使用try /除了爲了檢查不在Google模型中的單詞而遇到問題。每次出現異常時,我都可以打印該單詞,但模型會停止並且不會計算列表中剩餘的單詞。Try-Except與列表在Python中的問題

代碼後,我已經顯示詞彙列表的內容和模型停止在單詞遊客沒有改變其他單詞旅客後的單詞。我真的陷入困境,我可以在這一個上使用一些幫助。有任何想法嗎?

for x in range(0,len(data)): 
    titles.append(data[x]['title']) 
    paragraphs.append(data[x]['paragraphs']) 

model = gensim.models.Word2Vec.load('/tmp/models/google2') 
for y in range(95,96): 
    vocabulary.append(titles[y]) 
    vocabulary.append(paragraphs[y][0]) 
    vocabulary.append(paragraphs[y+1][0]) 
    print vocabulary 
    for entry in vocabulary: 
     try: 
      row = tokenizer.tokenize(entry) 
      row = [word for word in row if word not in stopwords.words('english')] 
      row = [model[item] for item in row] 
      row = [np.sum(item) for item in row] 
      last.append(row) 
     except KeyError,e: 
      print "There is a word that does not exist in the vocabulary: ", e 

有不詞彙表中存在的一句話:u'travellers'

詞彙[0]:亞洲的全球旅行熱潮

詞彙[1]:大陸的變化正在作出在旅遊,旅遊和消費能力方面,越來越多的亞洲人,特別是中國人,旅行者在海外冒險。

詞彙[2]:這是最近發生在中亞最窮的國家最令人興奮的事情。

預先感謝您。

回答

0

既然你把for y in range(95,96):一次循環

+0

它用於測試目的隊友。循環運行一次,並將3個值加載到詞彙表中。爲了產生設想的結果,不需要運行一次以上。例如第二個循環運行3次,因爲詞彙表中有3個值。即使你是正確的,這就是問題,計算應該停止在旅行者之前,而不是在那裏。 – Swan87 2014-08-29 00:09:39

0

你需要給它一個條件只能運行。像這樣:

for x in range(0,len(data)): 
    titles.append(data[x]['title']) 
    paragraphs.append(data[x]['paragraphs']) 

model = gensim.models.Word2Vec.load('/tmp/models/google2') 
for y in range(95,96): 
    vocabulary.append(titles[y]) 
    vocabulary.append(paragraphs[y][0]) 
    vocabulary.append(paragraphs[y+1][0]) 
    print vocabulary 
    for entry in vocabulary: 
     try: 
      row = tokenizer.tokenize(entry) 
      row = [word for word in row if word not in stopwords.words('english')] 
      # in your code, row will be overwritten several times, so I use new variables here 
      temp = [] 
      temp1 = [] 
      for item in row: 
       try: 
        model[item] 
       except KeyError, e: 
        continue 

       temp.append(model[item]) 
       temp1.append(np.sum(item)) 
       last.append(temp1) 
     except KeyError,e: 
      print "There is a word that does not exist in the vocabulary: ", e 

希望它有效。

+0

這是一個很好的方式來做到這一點,但我仍然得到: AttributeError:'Word2Vec'對象沒有屬性'has_key' – Swan87 2014-08-29 12:06:19

+0

@ Swan87好的。檢查我的更新。 – 2014-08-29 12:45:01

+0

還有當你做temp1.append作爲項目的錯誤(np.sum(項目))不numeric.I做: 爲行項目: 嘗試: \t打印項目 \t解析度= np.sum(模型[項目]) \t打印清晰度 \t temp.append(RES) 除了KeyError異常,E: 繼續 我的最後一個問題是,我需要纔能有每個單詞的數組的總和是在陣列中正確添加他們來自哪裏。例如對於[亞洲,全球,旅行,繁榮]這樣的句子來說,[-1.2136844,-1.4799396,-0.75583267,-1.0718837] – Swan87 2014-08-29 14:12:39