首页 > 解决方案 > Python 只读取最后一行,但我想要所有的,即使是同名

问题描述

我正在尝试编写一个函数,它将一个充满电影和收视率的 txt 文件放入字典中,但它的输出只读取了同名的最后一行这是我到目前为止所拥有的

def read_ratings_data(f):
    input = {}
    for line in open(f):
        movie, rating, numId = line.split('|')
        input[movie] = rating
    print(input)

txt 文件中的示例:

Toy Story (1995)|4.0|1
Toy Story (1995)|4.0|5
Toy Story (1995)|4.5|7
Toy Story (1995)|2.5|15
Toy Story (1995)|4.5|17
Toy Story (1995)|3.5|18
Jumanji (1995)|4.0|6
Jumanji (1995)|4.0|8
Jumanji (1995)|3.0|18
Jumanji (1995)|3.0|19
Jumanji (1995)|3.0|20
Jumanji (1995)|3.5|21

我的输出:

{'Toy Story (1995)': '3.5', 'Jumanji (1995)': '3.5'}

预期输出结构

{"The Lion King (2019)" : [6.0, 7.5, 5.1], "Titanic (1997)": [7]}

假设存储所有信息,包括同名电影。只取了同名的最后一行

标签: pythonpython-3.x

解决方案


根据您的评论,我了解您希望电影名称作为字典中的键来表示文本文件中电影评级的列表:

def read_ratings_data(f):
    movies = dict()
    # use a context manager so that it takes care
    # of exceptions and automatically closes the file
    with open(f) as file:
        for line in file:
            movie, rating, _ = line.strip().split('|')
            # if the dictionary already has the movie
            # it also means it has a corresponding list 
            # so just append to that list the rating
            if movie in movies.keys():
                movies[movie].append(rating)
            else:
                # if there is not yet a key
                # with the movie name
                # create a new key and as
                # the value use a list that contains
                # the rating
                movies[movie] = [rating]
    return movies


print(read_ratings_data('text.txt'))

'text.txt'将是您拥有数据的文件


推荐阅读