如何用Python读取电影评分文件并按评分排序?
How to Read and Sort Movie Ratings from a File in Python
Looks like you're on the right track, but let's fix and complete your code to properly parse the movie ratings and sort them correctly. Here's a polished, working version with explanations:
Corrected Code
def sort_movie_ratings(filename): # Initialize an empty list to hold our movie data as (title, rating) tuples movie_data = [] with open(filename, 'r') as file: for line in file: # Remove leading/trailing whitespace and skip empty lines cleaned_line = line.strip() if not cleaned_line: continue # Split the line into title and rating parts (handles spaces around commas) title_part, rating_part = cleaned_line.split(',') title = title_part.strip() # Convert rating from string to float (with error handling for invalid entries) try: rating = float(rating_part.strip()) except ValueError: print(f"Warning: Skipping invalid line (no valid rating): {cleaned_line}") continue # Add the parsed data to our list movie_data.append( (title, rating) ) # Sort the movies by rating (descending order for highest first; reverse=False for ascending) movie_data.sort(key=lambda x: x[1], reverse=True) return movie_data # Usage example if __name__ == "__main__": filename = "movie_ratings.txt" sorted_movies = sort_movie_ratings(filename) # Print the sorted results print("Movies sorted by rating (highest first):") for title, rating in sorted_movies: print(f"- {title}: {rating}/10")
Key Improvements & Explanations
- Proper Initialization: We start with an empty list
movie_datato store our parsed title-rating pairs (no undefined variables like your originaltitlelist). - Robust Parsing: We split each line on commas, then strip whitespace from both parts to handle the space around commas in your file example.
- Error Handling: The
try/exceptblock catches lines where the rating isn't a valid number, so your script won't crash if there's bad data. - Clear Sorting: Using
sort(key=lambda x: x[1], reverse=True)tells Python to sort using the second element of each tuple (the rating) in descending order. Removereverse=Trueif you want lowest-rated movies first. - Reusable Function: The function takes the filename as a parameter, making it easy to use with different files later.
Sample Output
For your provided file content, running this code will output:
Movies sorted by rating (highest first): - Lord of the Rings: The Two Towers: 8.7/10 - Harry Potter and the Prisoner of Azkaban: 7.8/10 - Kung Fu Panda: 7.6/10 - Spider Man: 7.3/10 - The Good Dinosaur: 6.7/10 - Alice in Wonderland: 6.5/10
内容的提问来源于stack exchange,提问作者Michael Marquez
相关产品推荐
相关产品推荐

