Detecting questions means identifying whether a sentence is interrogative or not. We can also use machine learning to detect questions, but since we all know the type of sentences we see in an interrogative sentence, it is also possible to write a Python script to detect whether a sentence is a question or not. So if you want to learn how to detect whether a sentence is a question or not, then this article is for you. In this article, I’ll walk you through how to write a program to detect questions using Python.
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.
Now below is how we can detect questions using Python by following the logic explained in the above section:
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 for x in question_words): print("This is a question!") else: print("This is not a question!")
Input a sentence: Do you have any feelings for me? This is a question!
So this is how you can easily detect whether a sentence is a question or not.
I hope you now have understood how to identify questions or interrogative sentences using Python. We can also use machine learning for detecting questions, but as we all know the kind of sentences we see in an interrogative sentence, so it is also possible to write a Python script for detecting whether a sentence is a question or not. I hope you liked this article on how to detect questions using Python. Feel free to ask your valuable questions in the comments section below.
thanks, keep visiting 🤝