How to print frequencies in descending order?

风格不统一 提交于 2019-12-20 04:03:46

问题


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]

Thanks in advance.


回答1:


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



回答2:


You can call items on the dict to get a list of tuples of the items in the dictionary. You can then (reverse) sort by the second item in the tuple (the value in the dict, the frequency):

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

By the way, rather than using 'ABCD..., you can use string.ascii_uppercase.




回答3:


Descending from Z to A? Change the string constant on the second last line to 'ZYXWV...A'.




回答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]


来源:https://stackoverflow.com/questions/10561566/how-to-print-frequencies-in-descending-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!