Python 查找最出现最多的字母
str=''' China has played a prominent role in offering great opportunities to world economic growth through digital transformation, Brazilian economist Alessandro Teixeira made the remarks in an interview on the sidelines of the Boao Forum for Asia Annual Conference 2022 in Boao, a coastal town in southern China's island province of Hainan. Teixeira, who used to be the Special Advisor of the President of Brazil and Deputy Minister of Development, Industry and International Trade of Brazil noted that China has played a huge role in digital transformation, a dding that China not only is one of the first countries in the world to offer the relevant technology, but also makes it possible in other countries. '''clear_str=str.lower().replace(' ','').replace('
','') ca=tuple(clear_str) x = set(ca) lett={} for i in x: lett[i] = clear_str.count(i) listw= [(k,v) for k,v in zip(lett.keys(),lett.values())] listw.sort(key=lambda x:x[1],reverse=True)print(f'最多的字母是{listw[0][0]},出现了{listw[0][1]}次')
clear_str 为 字符串
#如果不需要知道是多少次,那么
import string
print (max(string.ascii_letters, key=clear_str.count))
# string.ascii_uppercase 所有大写字母
# string.ascii_lowercase 所有小写字母
# string.ascii_letters 所有字母
# string.digits 所有数字
或者
from string import ascii_lowercase as letters
checkio = lambda text: max(letters, key=clear_str.lower().count)
#也可以是这样子的
import re
text = re.sub(r'[^a-zA-Z]', '', clear_str)
mydict = {}
for letter in set(text):
mydict[letter] = text.count(letter)
mylist = []
for each_item in mydict.keys():
if mydict[each_item] == max(mydict.values()):
mylist.append(each_item)
mylist.sort()
print (mylist)

评论