2017-06-09 68 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( “题”) ? –

相关问题