我有一个文件,其中有一个乐队的名单,专辑和它的制作年份。 我需要写一个函数来遍历这个文件,找到不同的波段名称,并计算出这些波段在这个文件中出现的次数。在
文件的外观如下:
Beatles - Revolver (1966)
Nirvana - Nevermind (1991)
Beatles - Sgt Pepper's Lonely Hearts Club Band (1967)
U2 - The Joshua Tree (1987)
Beatles - The Beatles (1968)
Beatles - Abbey Road (1969)
Guns N' Roses - Appetite For Destruction (1987)
Radiohead - Ok Computer (1997)
Led Zeppelin - Led Zeppelin 4 (1971)
U2 - Achtung Baby (1991)
Pink Floyd - Dark Side Of The Moon (1973)
Michael Jackson -Thriller (1982)
Rolling Stones - Exile On Main Street (1972)
Clash - London Calling (1979)
U2 - All That You Can't Leave Behind (2000)
Weezer - Pinkerton (1996)
Radiohead - The Bends (1995)
Smashing Pumpkins - Mellon Collie And The Infinite Sadness (1995)
.
.
.
输出必须按频率降序排列,如下所示:
^{pr2}$以下是我目前掌握的代码:
def read_albums(filename) :
file = open("albums.txt", "r")
bands = {}
for line in file :
words = line.split()
for word in words:
if word in '-' :
del(words[words.index(word):])
string1 = ""
for i in words :
list1 = []
string1 = string1 + i + " "
list1.append(string1)
for k in list1 :
if (k in bands) :
bands[k] = bands[k] +1
else :
bands[k] = 1
for word in bands :
frequency = bands[word]
print(word + ":", len(bands))
我想有更简单的办法,但我不确定。另外,我不知道如何按频率对字典排序,我需要把它转换成列表吗?在
我的方法是使用
split()
方法将文件行分成组成标记的列表。然后,您可以获取乐队名称(列表中的第一个标记),并开始将这些名称添加到字典中以跟踪计数:注意事项:
如果您想要简洁,请使用“defaultdict”和“sorted”
你说得对,有一个更简单的方法,使用^{} :
这条线是以下循环的长形式:
^{pr2}$但与上面的循环不同,它不会创建中间层。相反,它创建了一个generator expression-一种更节省内存的方法来逐步处理事情;它被用作
Counter
的参数。在相关问题 更多 >
编程相关推荐