我会用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()