I need to write a program to receive a file. her content is something like that:
hello;Adele;5:21 easy on me;Adele;2:31 My Way;FrankSinatra;3:45
this is my code:
def my_mp3_plyalist(file_path): f = open(file_path, "r") # count lines line_count = 0 for line in f: if line != "n": line_count += 1 f.close() # end count lines with open(file_path, 'r') as f: result = tuple() splited_lines = f.read().split() len_splited_lines = len(splited_lines) items = list() for line in range(len_splited_lines): items.append(splited_lines[line].split(';')) print(items) max_song_len = 0 longest_song_name = "" max_artist_apperance, most_appearing_artist = 0, "" artists = {} for i in items: song_len = float(i[-1].replace(':', '.')) if song_len > max_song_len: longest_song_name = i[0] for item in items: artist = item[0] if artist not in artists: artists[artist] = 0 artists[artist] += 1 most_appearing_artist, number_of_appearances = max(artists.items(), key=lambda x: x[1]) result = (longest_song_name, line_count, most_appearing_artist) return result def main(): print(my_mp3_plyalist(r"C:UsersuserDocumentswords.txt")) if __name__ == "__main__": main()
the program needs to return a tuple that contain the (name of the longest song, number of lines in the file, most appearing artist in the file)
('hello', 3, 'Adele')
But it doesn’t work and return:
('MyWay', 3, 'hello')
Advertisement
Answer
from collections import Counter with open("path/to/file") as f: lines = f.readlines() lines = tuple( map( lambda x: (x[0], x[1], float(x[-1])), map(lambda x: x.strip().replace(":", ".").split(";"), lines), ), ) longest = max(lines, key=lambda x: x[-1])[0] artists_count = Counter([el[1] for el in lines]) max_artists_count = max(artists_count, key=artists_count.get) obj = longest, len(lines), max_artists_count print(obj) # ('hello', 3, 'Adele')