如何计算字符串中出现频率最高的字母?

2024-10-01 13:37:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

    def findMostFrequentChar(self):
        # ?

我需要实现findMostFrequenctChar。她给我们的唯一暗示是我们需要列两张单子。这就是她失去我的地方。在

以下是调用函数的代码:

^{pr2}$

Tags: selflenreturninitdefcount地方class
3条回答

我会用口述来存储计数。 但是首先我要去掉所有的spaces和其他符号,然后是a-z,我还想把大写字母和小写字母计数为一个相同的数字。在

当dict用我的所有值构造时,我使用max函数。 max接受iterable,因此我们将dict作为元组(key, val)的“list”传递。我们需要告诉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()

The only hint she gave us was that we needed to make 2 lists. and this is where she lost me.

这似乎意味着你不能使用collections.Counter, 可能连字典都没有。在

如果我们可以假设字母被定义为英文字母, 一张单子就够了。 在这种情况下,可以创建一个包含26个项的列表,所有项都初始化为0。 然后你可以迭代字符串的字符, 对于英语字母表中的每个字母,递增列表中第n-项的计数,其中n是字母表中字母的索引。在

创建26个零的列表:

counts = [0] * 26

循环输入字符串s的字符:

^{pr2}$

检查字符是否为字母:

if 'a' <= c.lower() <= 'z'

计算字母表中字母的从0开始的索引,并递增计数:

index = ord(c.lower()) - ord('a')
counts[index] += 1

一旦你知道了, 您可以找到具有最大值的索引(作为练习留给您), 并用chr(index + ord('a'))得到相应的字符。在

您可以使用sorted

class String:
    def __init__(self, s):   
       self.s = s
    def findMostFrequentChar(self):
       return sorted([(a, self.s.count(a)) for a in self.s], key=lambda x:x[-1])[-1]

相关问题 更多 >