【问题标题】:Finding the next element value of a particular index in a Python list在 Python 列表中查找特定索引的下一个元素值
【发布时间】:2017-11-11 02:13:25
【问题描述】:

我有一个简单的 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
  • 在词表中可以找到。
  • @DraykoonD a+1 不是用来访问word_list 它是用来访问input_sentences

标签: python list nltk


【解决方案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]。
  • 哦,我明白了,那么What should I do(没有问号)仍然会失败
  • 是的,如果我说 elif (input_sentences[0] in question) 和 (input_sentences[1] in word_list): result.append("question") ?
  • 你关注错了! input_sentences[a + 1] 将总是失败,因为a 可以指向列表中的最后一个元素
猜你喜欢
  • 2021-07-16
  • 2019-10-10
  • 2021-06-25
  • 2019-11-11
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
  • 2019-09-19
  • 2023-03-24
相关资源
最近更新 更多