如何计算字符串中最常见的字母?

Amb*_*irl 6 python

class MyString:
    def __init__(self, myString):
        self.__myString = myString

    def countWord(self):
         count = len(self.__myString.split())
         return count

    def findMostFrequentChar(self):
        # ?
Run Code Online (Sandbox Code Playgroud)

我需要实施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()
Run Code Online (Sandbox Code Playgroud)

Dav*_*ern 1

我会使用字典来存储计数。但首先我想删除所有spaces和其他符号,然后 az,我还想将大写和小写字母视为一个且相同。

当用我的所有值构造字典时,我使用该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()
Run Code Online (Sandbox Code Playgroud)