Finding next item value at specific index in python list
I have a simple python program to determine if a sentence is a question or not.
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
But this makes the following mistake.
if input_sentences[a + 1] in word_list:
IndexError: list index out of range
I think the problem occurs when looking for the next value of the element a. Can anyone help me to solve this problem.
source to share
The problem is that it input_sentences.index(qestion)
might return the last index input_sentences
, which means there a + 1
will be one more than there are items in input_sentences
, and then calls IndexError
as you try to access an item in the list if input_sentences[a + 1] in word_list:
that doesn't exist.
You are logically checking that the "next item" is therefore incorrect, the last item in the list does not have a "next item". Looking at your dictionaries, the question, how What should I do
, will not be fulfilled, since it do
will be matched like a question word, but nothing happens after it (it is assumed that you strip punctuation). Therefore, you need to rethink how you define the question.
source to share