Answered step by step
Verified Expert Solution
Question
1 Approved Answer
ef read _ input _ file ( input _ file ) : Reads the input file and stores the data in a
ef readinputfileinputfile:
Reads the input file and stores the data in a dictionary.
Args:
inputfile str: The name of the input file.
Returns:
dict: A dictionary where keys are the number of seasons and values are lists of TV shows.
datadict # Initialize an empty dictionary to store the data
with openinputfile, r as file: # Open the input file in read mode
lines file.readlines # Read all lines from the file
for i in range lenlines: # Iterate over pairs of lines
seasons intlinesistrip # Parse the number of seasons
show linesistrip # Parse the TV show
if seasons in datadict: # Check if the number of seasons already exists in the dictionary
datadictseasonsappendshow # Append the show to the existing list of shows
else:
datadictseasonsshow # Create a new keyvalue pair
return datadict # Return the populated dictionary
def writeoutputkeysoutputfile, datadict:
Writes the sorted dictionary keys and associated TV shows to an output file.
Args:
outputfile str: The name of the output file.
datadict dict: The dictionary containing the TV show data.
with openoutputfile, w as file: # Open the output file in write mode
for key in sorteddatadict.keys: # Iterate over sorted keys of the dictionary
shows ; joindatadictkey # Join the shows associated with the key
file.writefkey: shows
# Write the keyvalue pair to the output file
def writeoutputtitlesoutputfile, datadict:
Writes the sorted TV show titles to an output file.
Args:
outputfile str: The name of the output file.
datadict dict: The dictionary containing the TV show data.
with openoutputfile, w as file: # Open the output file in write mode
for key in sorteddatadict.keys: # Iterate over sorted keys of the dictionary
for show in sorteddatadictkey: # Iterate over sorted shows associated with the key
file.writefshow # Write the show title
file.write
# Write a new line
def main:
Main function to orchestrate the program execution.
inputfile inputEnter the name of the input file: # Prompt user for input file name
outputkeysfile "outputkeys.txt # Set output file name for sorted keys
outputtitlesfile "outputtitles.txt # Set output file name for sorted titles
# Read input file and store data in a dictionary
datadict readinputfileinputfile
# Write sorted data to output files
writeoutputkeysoutputkeysfile, datadict
writeoutputtitlesoutputtitlesfile, datadict
# Print success message
printfResults have been written to outputkeysfile and outputtitlesfile
if namemain:
main # Call the main function to execute the program
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started