如何按降序打印频率? [英] How to print frequencies in descending order?

查看:90
本文介绍了如何按降序打印频率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过其他类似的问题,但是无法将答案应用于我的程序.目前,频率是按升序打印的,我该如何更改以使其按降序打印呢?

I've had a look at other similar questions already but haven't been able to apply the answers to my program. At the moment the frequencies are printed in ascending order, what do I change to make it print it in descending order?

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]

先谢谢了.

推荐答案

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

You don't have to reinvent the wheel. Use standard library features:

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

这篇关于如何按降序打印频率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆