Question: Please modify & correct the sentence - generator program of Case Study 5 - 1 ( in the file generator.py ) so that it inputs

Please modify & correct the sentence-generator program of Case Study 5-1(in the file generator.py) so that it inputs its vocabulary from a set of text files at startup. The filenames are nouns.txt, verbs.txt, articles.txt, and prepositions.txt.(Hint: Define a single new function, getWords. This function should expect a filename as an argument. The function should open an input file with this name, define a temporary list, read words from the file, and add them to the list. The function should then convert the list to a tuple and return this tuple. Call the function with an actual filename to initialize each of the four variables for the vocabulary.)
import random
def getWords(filename):
"""
Reads words from a given file and returns them as a tuple.
Args:
filename (str): The name of the file containing the words.
Returns:
tuple: A tuple containing all the words from the file.
"""
with open(filename,'r') as file:
words =[line.strip().upper() for line in file]
return tuple(words)
# Initialize vocabulary from text files
articles = getWords('articles.txt')
nouns = getWords('nouns.txt')
verbs = getWords('verbs.txt')
prepositions = getWords('prepositions.txt')
def sentence():
"""
Constructs a random sentence.
Returns:
str: A randomly generated sentence.
"""
return nounPhrase()+""+ verbPhrase()
def nounPhrase():
"""
Constructs a random noun phrase.
Returns:
str: A randomly generated noun phrase.
"""
return random.choice(articles)+""+ random.choice(nouns)
def verbPhrase():
"""
Constructs a random verb phrase.
Returns:
str: A randomly generated verb phrase.
"""
return random.choice(verbs)+""+ nounPhrase()+""+ prepositionalPhrase()
def prepositionalPhrase():
"""
Constructs a random prepositional phrase.
Returns:
str: A randomly generated prepositional phrase.
"""
return random.choice(prepositions)+""+ nounPhrase()
def main():
"""
Main function to generate and print random sentences.
"""
number = int(input('Enter the number of sentences: '))
for count in range(number):
print(sentence())
if __name__=='__main__':
main()

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!