2017-04-18 35 views
0

我試圖運行我的程序,但整個錯誤傳來:Python3:如何解決列表出界錯誤?

Traceback (most recent call last): 
    File "C:\myquestions\questansgen-script.py", line 11, in <module> 
    load_entry_point('questansgen==0.1', 'console_scripts', 'questansgen')() 
    File "c:\Python36\lib\site-packages\click\core.py", line 610, in __call__ 
    return self.main(*args, **kwargs) 
    File "c:\Python36\lib\site-packages\click\core.py", line 590, in main 
    rv = self.invoke(ctx) 
    File "c:\Python36\lib\site-packages\click\core.py", line 782, in invoke 
    return ctx.invoke(self.callback, **ctx.params) 
    File "c:\Python36\lib\site-packages\click\core.py", line 416, in invoke 
    return callback(*args, **kwargs) 
    File "C:\myquestions\questansgen\scripts\questansgen.py", line 22, in generate_trivia 
    questions = questions + article.generate_trivia_sentences() 
    File "C:\myquestions\questansgen\article.py", line 22, in generate_trivia_sentences 
    trivia = self.evaluate_sentence(sentence) 
    File "C:\myquestions\questansgen\article.py", line 100, in evaluate_sentence 
    trivia['similar_words'] = self.get_similar_words(replace_nouns[0]) 
    File "C:\myquestions\questansgen\article.py", line 39, in get_similar_words 
    hypernym = synset.hypernyms()[0] 
IndexError: list index out of range 

下面是代碼,是我實現,在錯誤發生:
Code file

請讓我知道我可以做些什麼來避免這種錯誤並輸入任何數量的文本進行處理。

+0

追溯的末端缺失(其中包含最終的除外)。 – lenz

+0

哦是的..讓我編輯它 –

+0

@lenz done..please現在檢查 –

回答

1

粗暴的方式try-except

def first_hypernym(ss): 
    try: 
     x = ss.hypernyms()[0] 
    except IndexError: 
     x = None 
    return x 

一個班輪if-else

first_hypernym = None if not ss.hypernyms() else ss.hypernyms()[0] 

爲了證明這一點:

>>> x = [] 
>>> y = None if not x else x[0] 
>>> y 
>>> 

Best way to check if a list is empty


在苦心啓發式/語言學方法:看https://github.com/alvations/pywsd/blob/master/pywsd/allwords_wsd.py#L29(免責聲明:無恥的插頭)