题目:从控制台输入或从文件中读入一段文本,统计出其中每个字符出现的次数,并按照出现次数排序输出。
例如:
History is his story.
输出:
s:4
i:3
:3
t:2
o:2
r:2
y:2
h:1
H:1
.:1
def count(string):
result_dict = {}
# 统计
for one in string:
result_dict[one] = result_dict.get(one,0) + 1
return sorted(result_dict.items(), key = lambda x:x[1],reverse=True)
if __name__ == "__main__":
# 判断是否输入空字符串
while True:
input_str = input("请输入文本: ")
if input_str.strip() != "":
break
print("请勿输入空字符串")
result = count(input_str)
print("----------------统计结果如下---------------")
for x,y in result:
print("{}: {}".format(x,y))