python计算字符串字母的位置_python – 如何计算字符串中最常见的字母?

我会用dict来存储计数.

但首先我要删除所有空格和其他符号然后a-z,我还要计算上限和下限.小写字母为同一个字母.

当用我的所有值构造dict时,我使用max函数.

max需要一个可迭代的,所以我们将dict作为元组(key,val)的“列表”传递.我们需要告诉max如何确定我们想要比较的内容,因为我们给出一个lambda函数,它将元组中的第二个元素(val)带到key-arg.

作为回报,max将吐出具有最高val的元组.

class MyString:

def __init__(self, myString):

self.__myString = myString

def countWord(self):

count = len(self.__myString.split())

return count

def findMostFrequentChar(self):

counter = {}

# Instead of performing various modifications on the string

# one can instead filter all the undesired chars.

# new_string = self.__myString.replace(' ', '').lower()

new_string = list(filter(lambda x: 'a' >= x <= 'z', self.__myString.lower()))

for char in new_string:

if char in counter:

counter[char] += 1

else:

counter[char] = 1

key, value = max(counter.items(), key=lambda x:x[1])

return value, key

def main():

aString = MyString("This is a super long long long string. Please help count me")

print("There are", aString.countWord(), "words in the string.")

count, letter = aString.findMostFrequentChar()

print("The most frequent character is", letter, "which appeared", count, "times")

main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值