统计文本中每个字符出现的次数,打印前三
初级版:(if-else + 冒泡排序)
res = {}
with open('demo.txt') as f:
for char in f.read().replace(' ',''):
if char in res:
res[char] = res[char] + 1
else:
res[char] = 1
res_list = res.items()
length = len(res_list)
for i in range(length - 1):
for j in range(length - 1):
if res_list[j][1] < res_list[j+1][1]:
res_list[j], res_list[j+1] = res_list[j+1], res_list[j]
for i in range(3):
print '%s count is %d' % (res_list[i][0],res_list[i][1])
进阶版:
res = {}
with open('SSHClient.py') as f:
for char in f.read().replace(' ',''):
res[char] = res.get(char,0) + 1
for c,num in sorted(res.items(),key=lambda x:x[1],reverse=True)[:3]:
print '%s count is %d' % (c,num)