Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Modify the sentence-generator program of Case Study sothat it inputs its vocabulary from a set of text files at startup.The filenames are nouns.txt, verbs. txt,

Modify the sentence-generator program of Case Study sothat it inputs its vocabulary from a set of text files at startup.The filenames are nouns.txt, verbs. txt, articles.txt, andprepositions.txt.

(HINT: Define a single new function, getWords.This function should expect a filename as an argument. The functionshould open an input file with this name, define a temporary list,read words from the file, and add them to the list. The functionshould then convert the list to a tuple and return this tuple. Callthe function with an actual filename to initialize each of the fourvariables for the vocabulary.)

CASE STUDY: Generating Sentences

Can computers write poetry? We’ll attempt to answer thatquestion in this case study by giving a program a few words to playwith.

REQUEST: Write a program that generates sentences.

ANALYSIS:

Sentences in any language have a structure defined by a grammar.They also include a set of words from the vocabulary of thelanguage. The vocabulary of a language like English consists ofmany thousands of words, and the grammar rules are quite complex.For the sake of simplicity our program will generate sentences froma simplified subset of English. The vocabulary will consist ofsample words from several parts of speech, including nouns, verbs,articles, and prepositions. From these words, you can build nounphrases, prepositional phrases, and verb phrases. From theseconstituent phrases, you can build sentences. For example, thesentence “The girl hit the ball with the bat” contains three nounphrases, one verb phrase, and one prepositional phrase. Table belowsummarizes the grammar rules for our subset of English.

Phrase Its Constituents

Sentence Noun phrase+ Verb Phrase

Noun Phrase Article = Noun

Verb Phrase Verb + Noun Phrase+ Prepositional phrase

Prepositionalphrase Preposition + Noun Phrase

The rule for Noun phrase says that it is an article followed by(+) a Noun. Thus, a possible noun phrase is “the bat.” Note thatsome of the phrases in the left column of above Table also appearin the right column as constituents of other phrases. Although thisgrammar is much simpler than the complete set of rules for Englishgrammar, you should still be able to generate sentences with quitea bit of structure.

The program will prompt the user for the number of sentences togenerate. The pro- posed user interface follows:

Enter the number of sentences: 3

THE BOY HIT THE BAT WITH A BOY

THE BOY HIT THE BALL BY A BAT

THE BOY SAW THE GIRL WITH THE GIRL

Enter the number of sentences: 2

A BALL HIT A GIRL WITH THE BAT

A GIRL SAW THE BAT BY A BOY

DESIGN:

Of the many ways to solve the problem in this case study,perhaps the simplest is to assign the task of generating eachphrase to a separate function. Each function builds and returns astring that represents its phrase. This string contains words drawnfrom the parts of speech and from other phrases. When a functionneeds an individual word, it is selected at random from the wordsin that part of speech. When a function needs another phrase, itcalls another function to build that phrase. The results, allstrings, are concatenated with spaces and returned.

The function for Sentence is the easiest. It just calls thefunctions for Noun phrase and Verb phrase and concatenates theresults, as in the following:

def sentence():

"""Builds and return asentence."""

return nounPhrase() +" " + verbPhrase + "."

The function for Noun phrase picks an article and a noun atrandom from the vocabulary, concatenates them, and returns theresult. We assume that the variables articles and nouns refer tocollections of these parts of speech and develop these later in thedesign. The function random.choice returns a random element fromsuch a collection.

def nounPhrase() :

"""Builds and return anoun Phrase."""

returnrandom.choice(articles) + " " + random.choice(nouns)

The design of the remaining two phrase-structure functions issimilar.

The main function drives the program with a count-controlledloop:

def main() :

"""Allow the users to input the number ofsentences to generate."""

number = int(input("Enter the number ofsentences: "))

for count in range(number):

print(sentence())

he variables articles and nouns used in the program’s functionsrefer to the collections of actual words belonging to these twoparts of speech. Two other collections, named verbs andprepositions, also will be used. The data structure used to rep-resent a collection of words should allow the program to pick oneword at random.

Because the data structure does not change during the course ofthe program, you can use a tuple of strings. Four tuples serve as acommon pool of data for the functions in the program and areinitialized before the functions are defined.

IMPLEMENTATION (Coding)

When functions use a common pool of data, you should define orinitialize the data before the functions are defined. Thus, thevariables for the data are initialized just below the importstatement.

See enclosed program generator.py

TESTING:

Poetry it’s not, but testing is still important. The functionsdeveloped in this case study can be tested in a bottom-up manner.To do so, you must initialize the data first. Then you can run thelowest-level function, nounPhrase, immediately to check itsresults, and you can work up to sentences from there.

On the other hand, testing can also follow the design, whichtook a top-down path. You might start by writing headers for all ofthe functions and simple return statements that return thefunctions’ names. Then you can complete the code for the sentencefunction first, test it, and proceed downward from there. The wiseprogrammer can also mix bottom-up and top-down testing asneeded.

Step by Step Solution

3.38 Rating (167 Votes )

There are 3 Steps involved in it

Step: 1

Heres an implementation of the program that generates sentences by reading vocabulary from text file... blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Accounting Information Systems

Authors: George H. Bodnar, William S. Hopwood

11th Edition

0132871939, 978-0132871938

More Books

Students also viewed these Programming questions

Question

Explain the importance of Human Resource Management

Answered: 1 week ago

Question

Discuss the scope of Human Resource Management

Answered: 1 week ago

Question

Discuss the different types of leadership

Answered: 1 week ago

Question

Write a note on Organisation manuals

Answered: 1 week ago