test4

.py

School

Chaffey College *

*We aren’t endorsed by this school

Course

1-24395

Subject

Industrial Engineering

Date

Apr 3, 2024

Type

py

Pages

1

Uploaded by BailiffMaskOpossum6 on coursehero.com

# Define a dictionary to map majors to labels major_labels = { "Civil Engineering": 1, "Computer Engineering": 2, "Electrical Engineering": 3, "Mechanical Engineering": 4 } # Prompt the user for the input file name input_file_name = input("Enter the input file name: ") # Keep looping until a valid input file is provided while True: try: with open(input_file_name, 'r') as input_file: lines = input_file.readlines() break except FileNotFoundError: print("File not found. Please enter a valid input file name.") input_file_name = input("Enter the input file name: ") # Generate the output file name output_file_name = input_file_name.split(".")[0] + "-out.txt" # Initialize counters for each major major_counters = {} for major in major_labels: major_counters[major] = 0 # Open the output file for writing with open(output_file_name, 'w') as output_file: # Loop through each line in the input file for line in lines: parts = line.strip().split(" ; ") name = parts[0] majors = parts[1:] major_labels_list = [] # Loop through each major in the majors list for major in majors: major_label = major_labels.get(major, 0) major_labels_list.append(str(major_label)) # Update major counters if the major is valid if major_label != 0: major_counters[major] += 1 output_line = name + " " + " ".join(major_labels_list) + "\n" output_file.write(output_line) # Write the major counts to the end of the output file with open(output_file_name, 'a') as output_file: # Loop through the major counters and write counts for each major for major, count in major_counters.items(): if count > 0: output_file.write(f"The number of {major} students: {count}\n") print(f"Output file '{output_file_name}' has been generated.")
Discover more documents: Sign up today!
Unlock a world of knowledge! Explore tailored content for a richer learning experience. Here's what you'll get:
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help