Home > Enterprise >  im trying to create a function to count genres from a text file list in python then save the amount
im trying to create a function to count genres from a text file list in python then save the amount

Time:12-06

The text file is formatted like so: artist, title, genre, play length, condition, stock, cost

the text file contains records of many genres which i need to add to a dictionary and count how many there are.

this is my code however when i run it, it returns 0 for each genre

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)

CodePudding user response:

Your function will fail silently if the genre isn't one of the ones in the list (e.g. if the case is wrong). Try this implementation:

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}")

This should work correctly if the file formatting is as you say it is, but it'll raise a KeyError if it encounters a genre that's not in the list. If that's what's happening, you can decide from there how to correct it.

CodePudding user response:

You should try

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