May-04-2018, 12:25 AM
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.
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)