字符串的实战 -- 返回字符串中出现次数最多的字母(次数相同则返回字母表中排最前面的字母)

⭐此次实战是从checkio游戏中的题目,具体网址:The Most Wanted Letter - python coding challenges - Py.CheckiO

●  首先熟悉下需求:给你一篇包含不同英文字母和标点符号的文本。你应该在课文中找到最常见的字母。返回的信件必须是小写。在检查最需要的字母时,大小写并不重要,因此为了便于搜索,“A”==“A”。确保您不计算标点符号、数字和空格,只计算字母。如果你有两个或多个相同频率的字母,那么返回拉丁字母表中最先出现的字母。例如,“one”只包含“o”、“n”、“e”一次,因此我们选择“e”。

 eg:输入:"How do you do?"    输出:"o"          

 eg:输入:"One"    输出:"e" 

 

 

提前了解一下需要用到的python的基本知识点

①:字符串去除两边的指定字符

# strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)。只能删除开头或是结尾的字符,不能删除中间部分的字符。
print(' hello world '.strip()) # 默认去除两边的空格
print('hello world!!!'.strip('!')) # 去除两边的感叹号
print('11111hello world11111'.strip('1')) # 去除两边的数字1

②:字符串替换指定字符

# replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
print(' hello world '.replace(' ','')) # 将所有的空格去除
print('hello-world'.replace('-','')) # 将所有的-去除

 

 ③:判断指定的字符串是否是数字

# isdigit() 方法检测字符串是否只由数字组成,只对 0 和 正数有效。
print('0'.isdigit()) # 返回布尔值
print('-1'.isdigit()) # 只对 0 和 正数有效
print('10'.isdigit()) # 只对 0 和 正数有效

④:排序(sorted() 函数

# sorted() 函数对所有可迭代的对象进行排序操作。
# sorted(iterable, cmp=None, key=None, reverse=False) reverse = True 降序 , reverse = False 默认升序

# 数字排序
li = [32,2,3,55,88,1034]
print('升序排序;',sorted(li))
print('降序排序;',sorted(li,reverse=True))

print('******************************')

# 字母排序
al_li = ['b','e','a','o','z','m']
print('升序排序;',sorted(al_li))
print('降序排序;',sorted(al_li,reverse=True))

 

 

 

接下来开始展示代码内容:

from collections import Counter
def checkio(text: str) -> str:
    text = text.lower() # 将字符串转化为小写
    text = text.strip('!').strip('?').replace(' ','').replace(',','').replace('-','') # 去除两边空格
    for i in text:
        # 判断是否是数字
        if i.isdigit():
            text = text.replace(i,'') # 将数字替换为空
    # 统计词频
    dic = dict(Counter(text))
    # 出现次数列表
    ctn_list = sorted(list(dic.values()),reverse=True)
    word_li = [] # 存放出现相同次数最多的字母
    
    # 判断词频是否相同
    if len(set(ctn_list)) == 1: # set去重后,长度为1,则证明所有字母出现次数一样
        # 获取最小的字母 sorted:默认升序
        return sorted(text)[0] # 获取最小的字母
    else: # 出现次数不相同
        for i in dic.keys():
            # 获取出现次数最多的字母 由于可能出现次数最多的字母会有多个
            if dic[i] == ctn_list[0]:
                # 存入word_li列表中
                word_li.append(i)
        return sorted(word_li)[0] #  再获取最小的字母
        
        

print("Example:")
print(checkio("Hello World!")) 
print(checkio("How do you do?") )
print(checkio("One") ) 
print(checkio("Oops!")) 
print(checkio("AAaooo!!!!") ) 
print(checkio("s-z") ) 
print(checkio("ssssssssssszfgssdsa11111111111111") )
print("The mission is done! Click 'Check Solution' to earn rewards!")

 

posted @ 2022-10-14 15:07  小小程序员-lian  阅读(107)  评论(0编辑  收藏  举报