I need to write a program to receive a file. her content is something like that:
JavaScript
x
4
1
hello;Adele;5:21
2
easy on me;Adele;2:31
3
My Way;FrankSinatra;3:45
4
this is my code:
JavaScript
1
45
45
1
def my_mp3_plyalist(file_path):
2
f = open(file_path, "r")
3
# count lines
4
line_count = 0
5
for line in f:
6
if line != "n":
7
line_count += 1
8
f.close()
9
# end count lines
10
with open(file_path, 'r') as f:
11
result = tuple()
12
splited_lines = f.read().split()
13
len_splited_lines = len(splited_lines)
14
items = list()
15
for line in range(len_splited_lines):
16
items.append(splited_lines[line].split(';'))
17
print(items)
18
19
max_song_len = 0
20
longest_song_name = ""
21
max_artist_apperance, most_appearing_artist = 0, ""
22
artists = {}
23
24
for i in items:
25
song_len = float(i[-1].replace(':', '.'))
26
if song_len > max_song_len:
27
longest_song_name = i[0]
28
for item in items:
29
artist = item[0]
30
if artist not in artists:
31
artists[artist] = 0
32
artists[artist] += 1
33
most_appearing_artist, number_of_appearances = max(artists.items(), key=lambda x: x[1])
34
35
result = (longest_song_name, line_count, most_appearing_artist)
36
return result
37
38
39
def main():
40
print(my_mp3_plyalist(r"C:UsersuserDocumentswords.txt"))
41
42
43
if __name__ == "__main__":
44
main()
45
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)
JavaScript
1
2
1
('hello', 3, 'Adele')
2
But it doesn’t work and return:
JavaScript
1
2
1
('MyWay', 3, 'hello')
2
Advertisement
Answer
JavaScript
1
19
19
1
from collections import Counter
2
3
with open("path/to/file") as f:
4
lines = f.readlines()
5
6
lines = tuple(
7
map(
8
lambda x: (x[0], x[1], float(x[-1])),
9
map(lambda x: x.strip().replace(":", ".").split(";"), lines),
10
),
11
)
12
13
longest = max(lines, key=lambda x: x[-1])[0]
14
artists_count = Counter([el[1] for el in lines])
15
max_artists_count = max(artists_count, key=artists_count.get)
16
obj = longest, len(lines), max_artists_count
17
print(obj)
18
# ('hello', 3, 'Adele')
19