Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading