繁体   English   中英

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

[英]How to count the most frequent letter in a string?

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()

她给我们的唯一暗示是我们需要制作2个名单。 这就是她失去我的地方。

这似乎意味着你不能使用collections.Counter ,甚至可能不是字典。

如果我们可以假设字母被定义为英文字母,那么一个列表就足够了。 在这种情况下,您可以创建一个包含26个项目的列表,全部初始化为0.然后您可以迭代字符串的字符,并对于英语字母表的每个字母,增加列表中第n个项目的计数,其中n是字母表中字母的索引。

创建一个包含26个零的列表:

counts = [0] * 26

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

for c in s:

检查字符是否为字母:

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]

如果您可以使用Counter from collections模块:

from collections import Counter

def findMostFrequentChar(self):
    d = Counter(self.__myString.replace(' ', '').lower())        
    return d.most_common()[0]

如果Counter

def findMostFrequentChar(self):
    d = {}

    for ch in self.__myString.replace(' ', '').lower():
        if ch in d:
            d[ch] += 1
        else:
            d[ch] = 1

    most_frequent = max(d, key=d.get)
    return most_frequent, d[most_frequent]

完全放在一起:

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

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

    def findMostFrequentChar(self):        
        d = {}

        for ch in self.__myString.replace(' ', '').lower():
            if ch in d:
                d[ch] += 1
            else:
                d[ch] = 1
        most_frequent = max(d, key=d.get)
        return most_frequent, d[most_frequent]


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.")

    letter, count = aString.findMostFrequentChar()
    print("The most frequent character is", letter, "which appeared", count, "times")

main()

我将向您展示如何通过使用没有任何导入的字典来获取常规字符串的最常用字母。 你的工作是相应地调整你的课程。

我假设如果两个或多个字母共享最高频率,则其中任何一个都是有效结果。

>>> s = 'aabacbcd'
>>> counts = {}
>>> for c in s:
...     counts[c] = counts.get(c, 0) + 1
... 
>>> counts
{'a': 3, 'c': 2, 'b': 2, 'd': 1}
>>> max(counts, key=counts.get)
'a'

我会用dict来存储计数。 但首先我要删除所有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()

“两个清单”部分令人生气。 但是,计算Python中可迭代元素的一个实用工具是collections.Counter

from collections import Counter

# ...
    def findMostFrequentChar(self):
        return Counter(self.__myString).most_common()[0][0]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM