Python 9.3.1 self.py课程-分拣文件数据的简单程序-dosent工作
在包含故障警告的txt文件上:Python 9.3.1 self.py课程-分拣文件数据的简单程序-dosent工作,python,Python,在包含故障警告的txt文件上: Tudo Bom;Static and Ben El Tavori;5:13; I Gotta Feeling;The Black Eyed Peas;4:05; Instrumental;Unknown;4:15; Paradise;Coldplay;4:23; Where is the love?;The Black Eyed Peas;4:13; 我正在尝试使用这个简单的程序: def my_mp3_playlist(file_path): wit
Tudo Bom;Static and Ben El Tavori;5:13;
I Gotta Feeling;The Black Eyed Peas;4:05;
Instrumental;Unknown;4:15;
Paradise;Coldplay;4:23;
Where is the love?;The Black Eyed Peas;4:13;
我正在尝试使用这个简单的程序:
def my_mp3_playlist(file_path):
with open(file_path, 'r') as playlist_file:
result_playlist_tuple = tuple() # Result tuple
playlist_splitted_lines = playlist_file.readlines()#.split("\n") # List of songs and additional data
len_of_playlist_splitted_lines = len(playlist_splitted_lines) # Getting list length instead of running a
# loop len(x) times
playlist_items = list()
for line in range(len_of_playlist_splitted_lines): # Extracting list of items from list of lines
playlist_items.append(playlist_splitted_lines[line].split(';'))
for element in playlist_items: # Deleting empty strings '' in playlist_lines
del element[-1]
del playlist_items[-1]
max_song_length, longest_song_name = 0, ""
max_artist_appearances, most_appearing_artist = 0, ""
for i in playlist_items:
# Getting max song length
curr_float_song_length = float(i[-1].replace(':', '.'))
if curr_float_song_length > max_song_length: # Getting max song length
max_song_length = curr_float_song_length
longest_song_name = i[0]
if i.count(i[1]) > max_artist_appearances: # Getting Most appearing song
max_artist_appearances = playlist_items.count(i)
most_appearing_artist = i[1]
result_playlist_tuple += (longest_song_name, len(playlist_items), most_appearing_artist)
return result_playlist_tuple
def main():
file_path = input("Enter file path: ")
print(my_mp3_playlist(file_path))
if __name__ == '__main__':
main()
程序需要返回元组:(str:longest\u歌曲,int:playlist\u项目(行),str:most\u艺术家)
我想要的输出:(“土豆条”,5,“黑眼豌豆”)
我得到的结果是:('Tudo Bom',3',Static和Ben El Tavori')*
请帮忙,
谢谢你,
Eyal.我想可能是关于这条线路的
del playlist_items[-1]
您可能试图删除最后一行,但您正在删除播放列表项目列表中的每一行。正如@JMCampos已经回答的那样,对于播放列表中的每一个元素,您将删除列表中最新的元素:
for element in playlist_items:
del element[-1]
del playlist_items[-1]
因此,您的项目列表将减半,只包含3行,而不是5行。您需要从循环中删除此行,如下所示:
del playlist_items[-1]
for element in playlist_items:
del element[-1]
playlist_items = [item for item in playlist_items if item]
但确保您拥有非空数据的更具python风格的方法是这样使用:
del playlist_items[-1]
for element in playlist_items:
del element[-1]
playlist_items = [item for item in playlist_items if item]
第三个结果参数是最常见的艺术家。您尝试在一条始终为1的直线上计算艺术家出现的次数。检查后,您计算最大外观数作为列表中整行的外观数(也始终为1,因为文件中没有重复的行):
有几种方法可以从列表中获取最频繁的值。例如,您可以在字典中收集您的艺术家及其歌曲数量,然后获得数量最高的艺术家:
artists = {}
for item in playlist_items:
artist = item[1]
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])