Answer:
Hi Aaliya! This is a very good question to answer in order to learn regular expression in general, and how to use them in Python. Please find the details below.
Step-by-step explanation:
The question is asking us to check if a given sentence follows a grammatical structure and return a confirmation if it is. How do we do this? We use regular expressions to match the format of the text. This is also the way email addresses are validated when we attempt to signup to a website and specify an email address that isn't recognized as a valid email address. To use regular expression in Python, we import the regular expression class called "re". We then define the acceptable format for a grammatically correct sentence with the code "sentence_regex = re.compile(r"\w+?(I|you|he|she|it)(?: is \w+?ing)(?: (\w+)$)"); ". The "\w" denotes an alphanumeric word, followed by the check for the pronoun I or you or he or she or it. The "|" means "or". Since the question is asking to check the present tense verb, we continue the regular expression definition to include "is \w+?ing" (to correctly match "is doing" something). Finally we expect any word in the end (denoted by (?: (\w+)$)) to be the object. Save the code below in a file called "gram_check.py" and have a play.
gram_check.py
import re;
import sys;
def gram_check(s):
sentence_regex = re.compile(r"\w+?(I|you|he|she|it)(?: is \w+?ing)(?: (\w+)$)");
if bool(re.match(sentence_regex, s)):
return "Grammatical"
else:
return "Ungrammatical"
s = input("Enter a sentence: ");
print(gram_check(s));