2016-02-13 116 views
0

我使用阿拉伯文字詞來查找同義詞;它工作正常使用下面的代碼,並將其輸出正確的同義詞:但是我要遍歷上面的一部分,我改字(YXZ)每次Python索引超出範圍?

import unicodedata 
from nltk.corpus import wordnet as wn 
yxz='work' 
jan = wn.synsets(yxz)[0] 
abc=jan.lemma_names(lang='arb') 
for bca in abc: #Converting from unicode to arabic done 
    nfkd_form = unicodedata.normalize('NFKD', bca) 
    encoded=nfkd_form.encode('utf-8')#this works fine 
    encoded= u"".join([c for c in nfkd_form if not unicodedata.combining(c)]) 
    print encoded 

,但它不工作,因爲指數是出範圍:(我有一個XML文檔我想要得到的動詞只在某些句子中的同義詞,動詞是標籤<v>之間存在的XML文檔中)

Synonyms=[] 

for phrase in root.findall('./PHRASE'): 
    ens = {en.get('x'): en.text for en in phrase.findall('en')} 
    if 'ORG' in ens and 'PERS' in ens: 
    if (((ens["ORG"] ==u"جامعة بيت لحم")and (ens["PERS"]==u" ه أحمد")) or ((ens["ORG"] ==u"جامعة كولومبيا.")and (ens["PERS"]==u"رئيس الجمهورية السيد محمد المنصف المرزوقي")) or ((ens["ORG"] ==u"معمل باريكادي ")and (ens["PERS"]==u"رئيس فنزويلا")) or ((ens["ORG"] ==u"شركة جوجل")and (ens["PERS"]==u"لاري بيدج وسيرغي برين")) or((ens["ORG"] ==u"محترفه الباريسي")and (ens["PERS"]==u"بول"))): 
    for v in phrase.findall('V'): 
        #----------------------------------------ENGLISH SYNONYM TRIAL--------------------------- 

      print("------ English Synonym Trial----------") 
      #-------Step 8.3] Google Translate API working fine) now want it to translate from ar to en from Diacritics---------- 
      #-----8.3.1] Translate Diactrics Array words to english----------------------- 
      gs = goslate.Goslate() 
      engVerb=gs.translate(unicode(v.text), 'en') #english word is the output 
      print("---EngVerb---") 
      print(engVerb) 
      #-----8.3.2] use Arabic Wordnet to get the synonyms[English->output unicode] Working ----------------------- 
      #yxz='work' 
      jan = wn.synsets(engVerb)[0] 
      abc=jan.lemma_names(lang='arb') 
      for bca in abc: #Converting from unicode to arabic done 
      nfkd_form = unicodedata.normalize('NFKD', bca) 
      encoded=nfkd_form.encode('utf-8')#this works fine 
      encoded= u"".join([c for c in nfkd_form if not unicodedata.combining(c)]) 
      #print encoded 
      Synonyms.append(encoded) 
print("----------------------------PRINTING SYNONYMS---------------------------") 
print Synonyms 

不過,我總是得到錯誤

jan = wn2.synsets(engVerb)[0] 

IndexError:列表索引超出範圍

回答

1

該錯誤意味着wn2.synsets(engVerb)是一個空列表(使用print調試,它幫助了很多),而你試圖訪問一個不存在的第一個元素。

試試這個:

x = wn2.synsets(engVerb) 
if len(x) == 0: 
    continue 
else: 
    jan = x[0]