use*_*700 2 python frequency letter
我已经看过其他类似的问题,但是无法将答案应用于我的程序。目前,频率是按升序打印的,我该如何更改以使其按降序打印?
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]
Run Code Online (Sandbox Code Playgroud)
提前致谢。
您不必重新发明轮子。使用标准库功能:
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
Run Code Online (Sandbox Code Playgroud)