我已经看过其他类似的问题,但无法将答案应用到我的程序中。目前频率按升序打印,我该如何更改才能使其按降序打印?
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]
提前致谢。
您不必重新发明轮子。使用标准库功能:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)