在Python列表中查找特定索引下一个元素的值

3

我有一个简单的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

我认为问题出在找到a的下一个元素值上。有人能帮我解决这个问题吗?


请检查您的代码中"a+1"是否超出了单词列表的范围,即a+1 < len(word_list)。 - Paltoquet
它在单词列表中可用。 - Chathuri Fernando
@DraykoonD a+1 不是用来访问 word_list 的,而是用来访问 input_sentences 的。 - Matti Lyra
1个回答

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将被视为问题词,但它后面没有任何内容(假设您去掉了标点符号)。因此,您需要重新考虑检测问题的方式。


首先,我已经检查了问题中的input_sentences[0]。 - Chathuri Fernando
哦,我明白了,那么 What should I do(没有问号)仍然会失败。 - Matti Lyra
如果我说elif (input_sentences[0] in question) and (input_sentences[1] in word_list): result.append("question"),是的。 - Chathuri Fernando
你的注意力放错了地方!input_sentences[a + 1]将会 永远 失败,因为 a 可能指向列表中的 最后一个 元素。 - Matti Lyra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接