Question 1: You are assisting a university event coordinator who has collected feedback messages from students after a guest lecture. Many of the comments are messy and inconsistently formatted, and your task is to clean the text before saving it in a report. One of the raw feedback is: “ THE SPEAKER WAS GREAT but THE ROOM WAS COLD ” Manipulate the string above by removing any leading and trailing spaces using strip() and converting all letters to lowercase with lower(). Manipulate the wording to standardize it by replacing "speaker" with "presenter" using replace(), then remove any extra internal spaces with " ".join(s.split()). Manipulate the cleaned text into title case using title() and display the final output using an f-string. Question 2: The event coordinator now wants to save and view the cleaned feedback created earlier. You will use Python’s file-handling features to write, read, and update the feedback stored in a text file. Implement file writing by creating a list called feedback_list that contains three cleaned feedback messages. Write them to a text file named feedback.txt, each on a new line. Implement file reading by opening feedback.txt and printing all feedback lines one by one. Implement file appending by adding one more feedback message to the same file, then read and print the full updated list again. Question 3: The event coordinator sometimes may try to open the feedback.txt file before it exists or while it is being used by another program. To prevent the program from crashing, you need to add exception handling that manages these file errors safely. Apply exception handling by placing your code for reading feedback.txt inside a try and except block. Apply specific error handling by printing: "File not found. Please create feedback.txt first." for FileNotFoundError "Permission denied. Close the file and try again." for PermissionError Apply a finally block to always print "Operation completed." whether the file is opened successfully or not. Question 4: The event coordinator wants to know how many students used the word “great” in their feedback. Using Python, you will analyze the contents of the feedback file, count mentions of this word, and create a short summary report. Implement a file-reading step that opens feedback.txt and reads all lines. Use lower() and find() (or the in operator) to count how many feedback entries contain the word “great” (case-insensitive). Implement a file-writing step that creates a new file named summary.txt and writes the following lines into it: === Workshop Feedback Summary === Total Feedback: X Mentions of 'Great': Y Implement a formatted print statement that displays the same summary neatly on the console using f-strings.
ScanSolve AI Answer
Here's how to solve these Python programming tasks for the SmartFit team.
Question 1: String Manipulation
Let's manipulate the feedback string step by step.
raw_feedback = " THE SPEAKER WAS GREAT but THE ROOM WAS COLD "
# Step 1: Remove leading/trailing spaces and convert to lowercase
cleaned_feedback_step1 = raw_feedback.strip().lower()
print(f"After strip() and lower(): '{cleaned_feedback_step1}'")
# Step 2: Replace "speaker" with "presenter" and remove extra internal spaces
# s.split() splits the string by any whitespace and returns a list of words.
# " ".join() then joins these words back with a single space, effectively removing extra internal spaces.
cleaned_feedback_step2 = " ".join(cleaned_feedback_step1.replace("speaker", "presenter").split())
print(f"After replace() and removing extra spaces: '{cleaned_feedback_step2}'")
# Step 3: Convert to title case
final_feedback = cleaned_feedback_step2.title()
# Step 4: Display the final output using an f-string
print(f"Final cleaned feedback: '{final_feedback}'")
Output:
After strip() and lower(): 'the speaker was great but the room was cold'
After replace() and removing extra spaces: 'the presenter was great but the room was cold'
Final cleaned feedback: 'The Presenter Was Great But The Room Was Cold'
Question 2: File Handling (Write, Read, Append)
We'll create a list of feedback messages, write them to a file, read them back, append a new message, and then read the updated file.
file_name = "feedback.txt"
# Step 1: Implement file writing
feedback_list = [
"The presenter was great but the room was cold.",
"Excellent content and engaging discussion.",
"More interactive sessions would be beneficial."
]
print("Writing initial feedback to feedback.txt...")
with open(file_name, 'w') as file:
for feedback in feedback_list:
file.write(feedback + "\n")
print("Initial feedback written successfully.")
# Step 2: Implement file reading
print("\nReading all feedback from feedback.txt:")
with open(file_name, 'r') as file:
for line in file:
print(line.strip()) # .strip() removes the newline character
# Step 3: Implement file appending
new_feedback_message = "The presentation was insightful and well-structured."
print(f"\nAppending new feedback: '{new_feedback_message}' to feedback.txt...")
with open(file_name, 'a') as file:
file.write(new_feedback_message + "\n")
print("New feedback appended successfully.")
# Step 4: Read and print the full updated list again
print("\nReading updated feedback from feedback.txt:")
with open(file_name, 'r') as file:
for line in file:
print(line.strip())
Output:
Writing initial feedback to feedback.txt...
Initial feedback written successfully.
Reading all feedback from feedback.txt:
The presenter was great but the room was cold.
Excellent content and engaging discussion.
More interactive sessions would be beneficial.
Appending new feedback: 'The presentation was insightful and well-structured.' to feedback.txt...
New feedback appended successfully.
Reading updated feedback from feedback.txt:
The presenter was great but the room was cold.
Excellent content and engaging discussion.
More interactive sessions would be beneficial.
The presentation was insightful and well-structured.
Question 3: Exception Handling
We'll apply try, except, and finally blocks to handle potential file errors when reading feedback.txt.
file_name = "feedback.txt" # This file should exist from Q2 for successful execution
print("\nAttempting to read feedback.txt with exception handling:")
try:
# Apply exception handling by placing code inside try block
with open(file_name, 'r') as file:
print("File opened successfully. Reading content:")
for line in file:
print(line.strip())
# Apply specific error handling for FileNotFoundError
except FileNotFoundError:
print("File not found. Please create feedback.txt first.")
# Apply specific error handling for PermissionError
except PermissionError:
print("Permission denied. Close the file and try again.")
# Apply a finally block to always print "Operation completed."
finally:
print("Operation completed.")
Output (assuming feedback.txt exists and is accessible):
Attempting to read feedback.txt with exception handling:
File opened successfully. Reading content:
The presenter was great but the room was cold.
Excellent content and engaging discussion.
More interactive sessions would be beneficial.
The presentation was insightful and well-structured.
Operation completed.
Question 4: Text Analysis and Summary Report
We'll read feedback.txt, count mentions of "great", and then create a summary file and print the summary to the console.
file_name = "feedback.txt"
summary_file_name = "summary.txt"
great_count = 0
total_feedback = 0
all_feedback_lines = []
# Step 1: Implement a file-reading step to count "great"
print("\nAnalyzing feedback for mentions of 'great'...")
try:
with open(file_name, 'r') as file:
for line in file:
all_feedback_lines.append(line.strip())
total_feedback += 1
# Use lower() and 'in' operator for case-insensitive check
if "great" in line.lower():
great_count += 1
except FileNotFoundError:
print(f"Error: {file_name} not found. Cannot generate summary.")
total_feedback = 0
great_count = 0
except Exception as e:
print(f"An unexpected error occurred while reading the file: {e}")
total_feedback = 0
great_count = 0
# Step 2: Implement a file-writing step for summary.txt
summary_content = [
"=== Workshop Feedback Summary ===",
f"Total Feedback: {total_feedback}",
f"Mentions of 'Great': {great_count}"
]
print(f"Writing summary to {summary_file_name}...")
with open(summary_file_name, 'w') as summary_file:
for s_line in summary_content:
summary_file.write(s_line + "\n")
print("Summary written successfully.")
# Step 3: Implement a formatted print statement for console display
print("\n--- Console Summary Report ---")
print(f"=== Workshop Feedback Summary ===")
print(f"Total Feedback: {total_feedback}")
print(f"Mentions of 'Great': {great_count}")
print("------------------------------")
Output (assuming feedback.txt contains the messages from Q2):
Analyzing feedback for mentions of 'great'...
Writing summary to summary.txt...
Summary written successfully.
--- Console Summary Report ---
=== Workshop Feedback Summary ===
Total Feedback: 4
Mentions of 'Great': 1
Still stuck on this one?
Ask a follow-up, and the answer starts from this question.