如何按降序打印频率?

时间:2012-05-12 06:25:07

标签: python frequency letter

我已经查看了其他类似的问题,但未能将答案应用到我的程序中。在频率按升序打印的那一刻,我应该更改什么来使其按降序打印?

from sys import argv
frequencies = {}
for ch in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
   frequencies[ch] = 0

for filename in argv[1:]:
    try:
        f = open(filename)
    except IOError:
        print 'skipping unopenable', filename
        continue

 text = f.read()                
 f.close()                      

 for ch in text:                
     if ch.isalpha():
         ch = ch.upper()
         frequencies[ch] = frequencies[ch] + 1

for ch in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
    print ch, frequencies[ch]

提前致谢。

4 个答案:

答案 0 :(得分:4)

您不必重新发明轮子。使用标准库功能:

from sys import argv
from collections import Counter

frequencies = Counter()

for filename in argv[1:]:
    with open(filename) as f:
        text = f.read()
    frequencies.update(ch.upper() for ch in text if ch.isalpha())

for ch, freq in frequencies.most_common():
    print ch, freq

答案 1 :(得分:2)

您可以在dict上调用items以获取字典中项目元组的列表。然后你可以通过元组中的第二项(dict中的值,频率)来反转sort

sorted(frequencies.items(), key=lambda x: -x[1])

顺便说一下,您可以使用string.ascii_uppercase

,而不是使用'ABCD...

答案 2 :(得分:0)

从Z下降到A?将最后一行的字符串常量更改为“ZYXWV ... A”。

答案 3 :(得分:0)

from sys import argv
tre="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

for filename in argv[1:]:
    with open(filename) as f:
        text = f.read()
        ttt=list(set(zip(tre,map(text.count,tre))))
        ttt1=sorted([[x[1],x[0]] for x in ttt])
        ttt1.reverse()
        ttt3=[[x[1],x[0]] for x in ttt1]
        for x in ttt3:
            print x[0],x[1]