Python Detect Questions Tutorial

Detecting questions is the task of identifying interrogative sentences within a given text. It involves understanding the syntax and semantics of language to recognize question patterns, such as the presence of interrogative words (e.g., who, what, why, when, where, how) and question marks.

In this tutorial,  we will learn how to write a program to detect questions using Python. To write a Python program to detect whether a sentence is a question or not, we first need to create a list of words that we see at the start of an interrogative sentence. For example, what is your name? where do you live?, in these two questions, “what” and “where” are the types of words we need to store in a python list. Next, to check if a sentence is a question or not, we need to check if any word from the list is present at the beginning of the sentence. If it is present, then the sentence is a question, and if it is not present, then the sentence is not a question.

The example below is how we can detect questions in Python by following the logic explained in the section above:

from nltk.tokenize import word_tokenize
question_words = ["what", "why", "when", "where", 
             "name", "is", "how", "do", "does", 
             "which", "are", "could", "would", 
             "should", "has", "have", "whom", "whose", "don't"]

question = input("Input a sentence: ")
question = question.lower()
question = word_tokenize(question)

if any(x in question[0] for x in question_words):
    print("This is a question!")
else:
    print("This is not a question!")

Output:

Input a sentence: What are you doing?
This is a question!

So this is how you can easily detect whether a sentence is a question or not.

In this tutorial you learned how to define questions or interrogative sentences in Python

#python  

Python Detect Questions Tutorial
6.70 GEEK