如何打印按降序排列的频率?(How to print frequencies in descendi

2019-06-25 08:41发布

我有一个看看其他类似的问题早已但一直没能解答适用于我的计划。 此刻的频率印刷升序排列,我该怎么改,使其打印按降序排列?

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]

提前致谢。

Answer 1:

您不必推倒重来。 使用标准库的特点:

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


Answer 2:

您可以拨打itemsdict来获得在字典中的项目的元组的列表。 然后,可以(反向) 排序由在元组(在该值的第二项dict ,频率):

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

顺便说一句,而不是用'ABCD... ,你可以使用string.ascii_uppercase



Answer 3:

降序从Z到A? 改变字符串的倒数第二行“ZYXWV ... A”不变。



Answer 4:

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]


文章来源: How to print frequencies in descending order?