gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:22:08 25 4
gpt4 key购买 nike

我有一个简单的 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 的下一个元素值上。谁能帮我解决这个问题。

最佳答案

问题是input_sentences.index(qestion)可以返回input_sentences的最后一个索引,也就是说a + 1会是一个比 input_sentences 中的元素大的元素,当您尝试访问 if input_sentences[a + 1] 中的列表元素时,这会导致 IndexError在 word_list: 中不存在。

您检查“下一个元素”的逻辑因此不正确,列表中的最后一个元素没有“下一个元素”。查看您的单词列表,像 What should I do 这样的问题将失败,因为 do 将被选为疑问词,但后面没有任何内容(假设您去掉标点符号)。因此,您需要重新考虑发现问题的方式。

关于python - 在 Python 列表中查找特定索引的下一个元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44451372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com