使用python查找字符串中最常用的字符

2024-04-25 04:33:52 发布

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

我编写了bellow函数来查找字符串中最频繁出现的字符,它很适合于:

  1. “你好,世界!”
  2. “你好吗?”
  3. “One”(如果字符串只有唯一的字母,则返回第一个字母字符)

以下字符串“Lorem ipsum dolor sit amet”失败。最常见的字母都有3次出现,结果是一个空字符串,而不是给我其中一个(它应该按字母顺序给第一个)

def frequent_char(text):

    charset = ''.join(sorted(text))

    maxcount = 0
    maxchar = None

    for item in charset.lower():
        charcount = text.count(item)

        if charcount > maxcount :
            maxcount = charcount
            maxchar = item

    return maxchar

我不知道我在密码里犯了什么错误。有人能帮忙吗?


Tags: 函数字符串text字母世界item字符one
3条回答

删除字符串中的所有空格以使其正常工作。

def frequent_char(text):

    charset = ''.join(sorted(text))
    textTmp = text.replace(" ", "")  # add this to remove spaces
    maxcount = 0
    maxchar = None
    for item in charset.lower():
        charcount = textTmp.count(item)

        if charcount > maxcount:
            maxcount = charcount
            maxchar = item

return maxchar

一个很好的解决方案是使用collections.Counter,请参见:http://docs.python.org/2/library/collections.html#counter-objects

>>> counter = Counter('Lorem ipsum dolor sit amet')

最常见的字符是:

>>> counter.most_common(1)
[(' ', 4)]

如果你不在乎空间:

>>> counter.most_common(2)[1]
('m', 3)

很简单!

空间 has four occurences in Lorem ipsum dolor sit amet

所以如果你的问题是

to find the most frequent occurrences of a char in a string

你的功能发挥得很有魅力。

编辑:

因为你在问题中同时使用了“char”和“letter”,所以不完全清楚你在问什么。因为在Python中,“char”是一个比“letter”简单得多的概念,所以我决定将您的问题解释为一个关于char的问题。

相关问题 更多 >