Python 查找最出现最多的字母

本文介绍Python中查找字符串中出现次数最多的字母的多种方法,包括使用字典统计、max函数结合string.ascii_letters、以及正则表达式过滤非字母字符后统计,附有代码示例。

作者:zhuge···预计阅读 7 分钟·621 阅读·0 评论
Python 查找最出现最多的字母

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)

相关文章

评论

加载中...