2017-06-09 70 views
3

我有一個簡單的python程序來查找句子是否是問題。在Python列表中查找特定索引的下一個元素值

from nltk.tokenize import word_tokenize 
from nltk.stem.wordnet import WordNetLemmatizer 

a = ["what are you doing","are you mad?","how sad"] 
question =["what","why","how","are","am","should","do","can","have","could","when","whose","shall","is","would","may","whoever","does"]; 
word_list =["i","me","he","she","you","it","that","this","many","someone","everybody","her","they","them","his","we","am","is","are","was","were","should","did","would","does","do"]; 

def f(paragraph): 
    sentences = paragraph.split(".") 
    result = [] 

    for i in range(len(sentences)): 

    token = word_tokenize(sentences[i]) 
    change_tense = [WordNetLemmatizer().lemmatize(word, 'v') for word in token] 
    input_sentences = [item.lower() for item in change_tense] 

    if input_sentences[-1]=='?': 
     result.append("question") 

    elif input_sentences[0] in question: 
     find_question = [input_sentences.index(qestion) for qestion in input_sentences if qestion in question] 
     if len(find_question) > 0: 
      for a in find_question: 
       if input_sentences[a + 1] in word_list: 
        result.append("question") 
       else: 
        result.append("not a question") 
    else: 
     result.append("not a quetion") 

return result 
my_result = [f(paragraph) for paragraph in a] 
print my_result 

但它會產生以下錯誤。

if input_sentences[a + 1] in word_list: 
IndexError: list index out of range 

我覺得問題的原因找到了一個的下一個元素值。任何人都可以幫助我解決這個問題。

+0

只是檢查你的「a + 1」是否超出了單詞列表中的範圍,a + 1

+0

它在單詞表中可用。 –

+0

@DraykoonD'a + 1'不用於聲明'word_list'用於訪問'input_sentences' –

回答

1

的問題是input_sentences.index(qestion)可以返回input_sentences最後一個索引,這意味着a + 1會以外還有input_sentences元素一個更大的,這進而導致IndexError與您試圖訪問該列表的元素在if input_sentences[a + 1] in word_list:這不存在。

您是檢查「下一個元素」的邏輯因此是不正確的,列表中的最後一個元素沒有「下一個元素」。看看你的單詞列表,像What should I do這樣的問題將會失敗,因爲do會被挑出來作爲問題單詞,但是它後面什麼也沒有(假設你去掉了標點符號)。所以你需要重新思考你發現問題的方式。

+0

對於首先我檢查了input_sentences [0]。 –

+0

哦,我看,那麼'我該怎麼做'(沒有問號)仍然會失敗 –

+0

是的,如果我說elif(input_sentences [0]有問題)和(input_sentences [1]在word_list中): result.append( 「題」) ? –

相關問題