56.9k views
5 votes
Build a grammar checker function gram_check that takes as an input, sentences of the form [Pronoun] [present tense verb] [object] ex., He plays basketball and ensures that there is a subject-verb agreement; i.e. it distinguishes between He plays basketball and *You plays basketball. Important notes: The subject can be any of I, you, he, she, it, they. The verb can be any regular verb. The object can be any object. Your program must print "Grammatical" if the sentence is grammatical and "Ungrammatical" if the sentence is ungrammatical. Some structure within gram_check has been provided below, but you may change it if you wish. However, do not change the name of the function.import re def gram check(s): #Put your code here if #Put your code here return "Grammatical" else: return Ungrammatical" gram check("she play basketball")Out [11]: 'Ungrammatical'

1 Answer

7 votes

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));

User Martijn Kooij
by
4.4k points