Python设计解答

读取附件是一篇英文短文,请编写程序统计这篇短文前 n 行中每一个英文字母出现的次数,结果按次数降序排列,次数相同时,按字母表顺序输出。若 n 值大于短文行数,输出整篇文章中每一个英文字母出现的次数(大写字母按小写字母统计)。
The Old Man and the Sea.txt

f = open('The Old Man and the Sea.txt')
lines = f.readlines()
f.close()

n = int(input())
if n < len(lines):
    lines = lines[:n]

freqs = {}

for line in lines:
    for char in 'abcdefghijklmnopqrstuvwxyz':
        freqs[char] = freqs.get(char, 0) + line.lower().count(char)

freqs = dict(sorted(freqs.items(), key=lambda x: (-x[1], x[0])))

for k, v in freqs.items():
    print(f'{k}: {v}')