Python Forum

Full Version: Find how many times a user played an artist and how many times
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Need help refining this code.

artist_data.txt
1134999 Metallica
6821360 Aerosmith
10113088 Mozart
10151459 Queen

user_artist_data
1000002 1134999 33
1000002 6821360 8
1000002 10113088 144
1000002 10151459 5

how to I print:
Metallica, 33
Aerosmith, 8
Mozart, 144
Queen,5

Code below.

def file_reader(file_name,splt,clean):
    f = open(file_name, "r")
    file = f.readlines()
    f.close()
    file_split = []
    artist_dict = {}
    if clean == False:
        for r in range(len(file)):
            file_split.append(file[r].split(splt))
    else:
        for r in range(len(file)):
            temp = file[r].split(splt)
            if len(temp) < 2:
                continue
            else:
                artist_dict[temp[0]] = temp[1].rstrip("\n")
        return artist_dict

def artist_finder(userID,list_file):
    artist_count = []
    for row in list_file:
        if userID in row:
            del row[0]
            artist_count.append(row)
    if  len(artist_count) == 0:
        print("Artist not found")
    return  artist_count

def artistdata_printer(artist_count,artist_dict):
    if len(artist_count) == 0:
        print("Enter a valid Listener ID")
    else:
        for artist in artist_count:
            try:
                print(artist_dict[artist[0]].rstrip("\n"), end= " ")
                print(artist[1].rstrip("\n"))
            except KeyError:
                print(artist[0].rstrip("\n"), "Artist not found")

def printListenerTimesPlayed(userID):
    user_artist_data = file_reader("user_artist_data.txt"," ",False)
    artist_data = file_reader("artist_data.txt", "\t", True)
    if type(userID) == int:
        userID = str(userID)
    artist_count = artist_finder(userID,user_artist_data)
    artistdata_printer(artist_count,artist_data)

printListenerTimesPlayed(1000002)
Without using heavy tools like a Sqlite database (although what you are asking is just a query, so maybe it is worth looking at it)

def split_lines(fd, n):
    for line in fd:
        parts = line.split()
        if len(parts) == n:
            yield parts

class MusicDB:
    def __init__(self, artist, users):
        self.artist = {aid: name for aid, name in split_lines(artist, 2)}
        self.users = {}
        for uid, aid, n in split_lines(users, 3):
            self.users.setdefault(uid, {})[aid] = int(n)

    def report(self, uid):
        if uid not in self.users:
            print(f'User {uid} not in DB')

        for aid, n in self.users[uid].items():
            name = self.artist.get(aid, 'Unknown')
            print(f'{name}: {n}')

def main():
    with open('artist.txt', 'rt') as artist, open('user.txt', 'rt') as users:
        db = MusicDB(artist, users)

    db.report('1000002')

if __name__ == '__main__':
    main()