如何计算字符串中最频繁出现的字母?
问题内容:
class MyString:
def __init__(self, myString):
self.__myString = myString
def countWord(self):
count = len(self.__myString.split())
return count
def findMostFrequentChar(self):
# ?
我需要实施findMostFrequenctChar
。她给我们的唯一提示是,我们需要列出2个清单。这就是她失去我的地方。
这是调用该函数的代码:
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()
问题答案:
我会用字典来存储计数。但是首先我要剥离所有spaces
其他符号,然后再剥离az,我还想将大写和小写字母视为一个相同。
当使用我所有的值构建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()