2

我已经看过其他类似的问题,但无法将答案应用于我的程序。目前频率按升序打印,我要更改什么以使其按降序打印?

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

4 回答 4

5

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

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
于 2012-05-12T06:43:51.503 回答
2

您可以调用itemsdict获取字典中项目的元组列表。然后,您可以(反向)按元组中的第二项(中的值,频率)排序:dict

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

顺便说一句,'ABCD...您可以使用string.ascii_uppercase.

于 2012-05-12T06:30:07.253 回答
0

从 Z 下降到 A?将倒数第二行的字符串常量更改为“ZYXWV...A”。

于 2012-05-12T06:27:46.433 回答
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]
于 2012-05-12T09:19:07.207 回答