[Python] 7.9 LAB: Sorting TV Shows (dictionaries and lists)

Discussão em 'Python' iniciado por Stack, Fevereiro 15, 2025.

  1. Stack

    Stack Membro Participativo

    I've been stuck on this problem for several hours now and I'm at an impasse.

    Task


    Write a program that first reads in the name of an input file and then reads the input file using the file.readlines() method. The input file contains an unsorted list of the number of seasons followed by the corresponding TV show. Your program should put the contents of the input file into a dictionary where the number of seasons are the keys, and a list of TV shows are the values (since multiple shows could have the same number of seasons).

    Sort the dictionary by key (least to greatest) and output the results to a file named output_keys.txt, separating multiple TV shows associated with the same key with a semicolon (;). Next, sort the dictionary by values (alphabetical order), and output the results to a file named output_titles.txt.

    Ex: If the input is:

    file1.txt

    and the contents of file1.txt are:

    20
    Gunsmoke
    30
    The Simpsons
    10
    Will & Grace
    14
    Dallas
    20
    Law & Order
    12
    Murder, She Wrote


    the file output_keys.txt should contain:

    10: Will & Grace
    12: Murder, She Wrote
    14: Dallas
    20: Gunsmoke; Law & Order
    30: The Simpsons


    and the file output_titles.txt should contain:

    Dallas
    Gunsmoke
    Law & Order
    Murder, She Wrote
    The Simpsons
    Will & Grace


    Note: There is a newline at the end of each output file, and file1.txt is available to download.

    Problem


    The issue I'm running into is that I can get file1.txt to load but, when add file2.txt I'm getting errors all over the place.

    [​IMG]

    Attempted Solution


    def read_file(file1):
    """
    Reads the input file and parses it into a dictionary
    with seasons as keys and lists of TV shows as values.
    """
    dict1 = {}
    try:
    with open(file1, 'r') as f:
    file_lines = f.readlines()

    for i in range(0, len(file_lines) - 1, 2):
    if file_lines.strip() == '':
    continue

    # Parse season and shows
    season = int(file_lines.strip())
    show = file_lines[i + 1].strip()

    # Append to dictionary
    if season in dict1:
    dict1[season].append(show)
    else:
    dict1[season] = [show]

    print(f"Parsed: Season {season}, Show '{show}'")
    except FileNotFoundError:
    print(f"Error: File '{file1}' not found.")
    return None
    except ValueError as e:
    print(f"Error while reading the file: {e}")
    return None

    return dict1


    def output_keys(output_file, dict1):
    """
    Writes the dictionary to a file sorted by season numbers.
    """
    try:
    with open(output_file, 'w') as q:
    for key in sorted(dict1.keys()):
    shows = '; '.join(sorted(dict1[key]))
    q.write(f"{key}: {shows}\n")
    print(f"{key}: {shows}")
    except Exception as e:
    print(f"Error writing to file '{output_file}': {e}")


    def output_titles(output_file, dict1):
    """
    Writes all TV shows in alphabetical order to a file.
    """
    try:
    titles = []
    for shows in dict1.values():
    titles.extend(shows)

    with open(output_file, 'w') as o:
    for title in sorted(titles):
    o.write(f"{title}\n")
    print(title)
    except Exception as e:
    print(f"Error writing to file '{output_file}': {e}")


    def main(file1):
    """
    Main function to read input file, process data, and generate outputs.
    """
    dict1 = read_file(file1)
    if dict1 is None:
    print(f"Error: Invalid file name or processing issue: {file1}")
    return

    # Output files
    output_filename_keys = 'output_keys.txt'
    output_filename_titles = 'output_titles.txt'

    # Write outputs
    output_keys(output_filename_keys, dict1)
    output_titles(output_filename_titles, dict1)


    # Get input file from user
    if __name__ == "__main__":
    file_name = input()
    main(file_name)

    Continue reading...

Compartilhe esta Página