Question: Modify the sentence - generator program of Case Study 5 - 1 ( in the file generator.py ) so that it inputs its vocabulary from

Modify 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.)(LO: 5.1,5.2)
Please modify the program below:
# stats.py
import random def get_words(filename):
"""
Get words from a text file and return them as a tuple.
"""
try:
with open(filename,'r') as file:
words =[word.strip() for word in file.readlines()]
return tuple(words)
except FileNotFoundError:
print(f"File '{filename}' not found.")
return ()
def generate_sentence(nouns, verbs, articles, prepositions):
"""
Generate a random sentence based on the given vocabulary.
"""
sentence ="".join([
random.choice(articles),
random.choice(nouns),
random.choice(verbs),
random.choice(articles),
random.choice(nouns),
random.choice(prepositions),
random.choice(articles),
random.choice(nouns)
])
return sentence.capitalize()+"."
def main():
"""
Main function to generate a random sentence.
"""
# Get words from text files
nouns = get_words("nouns.txt")
verbs = get_words("verbs.txt")
articles = get_words("articles.txt")
prepositions = get_words("prepositions.txt")
# Generate and print a random sentence
if not all((nouns, verbs, articles, prepositions)):
print("Error: Unable to generate sentence. Missing vocabulary.")
else:
sentence = generate_sentence(nouns, verbs, articles, prepositions)
print("Random Sentence:", 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 Databases Questions!