Python Forum
Find how many times a user played an artist and how many times
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Find how many times a user played an artist and how many times
#1
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)
Reply
#2
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()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Student project - alert action when X happens Y amt of times, how? unknown00 2 1,781 Aug-25-2021, 08:07 PM
Last Post: namarang
  Finding how many times substring is in a string using re module ranbarr 4 2,944 May-21-2021, 06:14 PM
Last Post: nilamo
  Task-Throw a dice 10 Times tjm 3 4,597 Mar-17-2021, 07:21 PM
Last Post: perfringo
  Get Spotify Artist URI (Python beginner) Schar07 0 1,442 Nov-18-2020, 10:39 AM
Last Post: Schar07
  Print name N times using recursion ift38375 7 7,920 Oct-23-2019, 05:33 PM
Last Post: ichabod801
  How many times it was pressed the button chano 4 3,135 Aug-20-2019, 07:06 AM
Last Post: chano
  Subtacting times Confused 2 2,671 Apr-10-2019, 05:13 PM
Last Post: nilamo
  [split] Calculate Times dhodgens 3 2,838 Mar-03-2019, 09:30 PM
Last Post: micseydel
  times greater number than the previous rhai 4 3,434 Oct-08-2018, 03:27 AM
Last Post: woooee
  Adding and Removing coins to match Coin Bag Total infinite times Strayfe 8 4,587 Sep-11-2018, 07:30 PM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020