Question: How can I make it so this code doesn't have an error in the output and generates random shakspeare phrases for each different file. import

How can I make it so this code doesn't have an error in the output and generates random shakspeare phrases for each different file.
import random
def load_phrases(filename):
"""
Reads data from a file and returns a list of phrases.
Each line in the file represents one phrase.
:param filename: The name of the file to read
:return: A list of phrases from the file
"""
try:
with open(filename,'r') as file:
return [line.strip() for line in file]
except FileNotFoundError:
print(f"Error: The file {filename} does not exist.")
return []
def select_random(phrase_list):
"""
Selects a random phrase from a list.
:param phrase_list: List of phrases
:return: A randomly selected phrase
"""
return random.choice(phrase_list) if phrase_list else "UNKNOWN"
def combine_insult(phrase, adj1, adj2, noun):
"""
Combines the given phrases into a Shakespearean-style insult.
:param phrase: The introductory phrase
:param adj1: The first adjective
:param adj2: The second adjective
:param noun: The noun
:return: A formatted insult string
"""
return f"{phrase} Thou {adj1}{adj2}{noun}!"
def main():
"""
Controls the program by generating insults in a loop until the user decides to stop.
"""
# Load phrases from files
phrases = load_phrases('phrases.txt')
adjectives1= load_phrases('adj1.txt')
adjectives2= load_phrases('adj2.txt')
nouns = load_phrases('nouns.txt')
if not (phrases and adjectives1 and adjectives2 and nouns):
print("Error: One or more files could not be loaded. Exiting program.")
return
print("Welcome to the Shakespearean Insult Generator!")
print("Generate insults to your heart's content, or type 'stop' to exit.")
while True:
# Generate a random insult
phrase = select_random(phrases)
adj1= select_random(adjectives1)
adj2= select_random(adjectives2)
noun = select_random(nouns)
insult = combine_insult(phrase, adj1, adj2, noun)
# Display the insult
print("
"+ insult)
# Ask if the user wants another insult
user_input = input("
Would you like another insult? (yes/stop): ").strip().lower()
if user_input == 'stop':
print("Goodbye, thou art truly magnificent!")
break
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!