我正在尝试创建一个函数来计算 python 中文本文件列表中的流派,然后将每种流派的数量保存到我可以显示的变量中

im trying to create a function to count genres from a text file list in python then save the amount of each genre to a variable i can display

文本文件的格式如下: 艺术家、标题、流派、播放时长、状况、库存、成本

文本文件包含许多类型的记录,我需要将其添加到字典并计算有多少。

这是我的代码,但是当我 运行 它时,它 returns 每个类型 0

def count_genres():
file = open("RECORD_DATA.txt", 'r')

rock = 0
classical = 0
pop = 0
jazz = 0
spoken_word = 0


for row in file:
    if not row[0] == "#":
        row = row.rstrip()
        row = row.split(",")
        genre = str(row[2])

        if genre == "Rock":
            rock += 1
        elif genre == "Classical":
            classical += 1
        elif genre == "Pop":
            pop += 1
        elif genre == "Jazz":
            jazz += 1
        elif genre == "Spoken Word":
            spoken_word += 1
    
print("Amount of Records in each genre ")
print("Rock: ", rock)
print("Classical: ", classical)
print("Pop: ", pop)
print("Jazz: ", jazz)
print("Spoken Word: ", spoken_word)

你应该试试

with open("RECORD_DATA.txt", 'r') as file:
    for row in file:
        ....

如果流派不是列表中的流派之一(例如,如果大小写错误),您的函数将无提示地失败。试试这个实现:

def count_genres():
    genres = {genre: 0 for genre in(
        "Rock", "Classical", "Pop", "Jazz", "Spoken Word"
    )}
    with open("RECORD_DATA.txt") as file:
        for row in file:
            row = row.rstrip()
            if not row or row[0] == "#":
                continue
            genres[row.split(",")[2]] += 1

    print("Amount of Records in each genre ")
    for genre, count in genres.items():
        print(f"{genre}: {count}")

如果文件格式与您所说的一样,这应该可以正常工作,但如果遇到列表中没有的类型,它会引发 KeyError。如果出现这种情况,您可以从那里决定如何纠正它。