You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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_data to store our parsed title-rating pairs (no undefined variables like your original title list).
  • 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/except block 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. Remove reverse=True if 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:22:16