1042 字符统计 (20分)
请编写程序,找出一段给定文字中出现最频繁的那个英文字母。
输入格式:
输入在一行中给出一个长度不超过 1000 的字符串。字符串由 ASCII 码表中任意可见字符及空格组成,至少包含 1 个英文字母,以回车结束(回车不算在内)。
输出格式:
在一行中输出出现频率最高的那个英文字母及其出现次数,其间以空格分隔。如果有并列,则输出按字母序最小的那个字母。统计时不区分大小写,输出小写字母。
输入样例:
This is a simple TEST. There ARE numbers and other symbols 1&2&3...........
输出样例:
e 7
这个题可以使用re库中的sub函数利用正则表达式来将所有非字母的字符都替换为空,然后再使用一个字典来统计替换后的字符串中的各种字符的数量,最后以字典的value和key作为排序的key进行排序并输出最大值即可。
代码:
import re
#用空替换掉所有字母以外的其他字符
#Replace other characters except letters with empty
#^[a-z] :正则表达式,表示除了字母a-z之外的其他所有字符
a=re.sub('[^a-z]','',input().lower())
b={}
for i in a:
#字符不在字典中,则加入,并且数量加一
#Character not in dictionary,just join it,and the number increases plus one
#字符在字典中,则数量加一
#Character in dictionary,then the number increases plus one
if i not in b:
b[i]=0
b[i]=b[i]+1
c=list(b.items())
#先按value进行排序,再按key进行排序
#Sort by value first,sort by key again
c=sorted(c,key=lambda x:(-x[1],x[0]),reverse=False)
#按格式输出最大值
#Output maximum value in format
print(str(c[0][0])+' '+str(c[0][1]))