python - python 字符串中出现频率最高的一个或多个字母

标签 python string

问题要求我返回一个小写字符串,其中包含按字母顺序排列的 s 中最常出现的字母。到目前为止我已经:

def mostFrequentLetter(s):
    allchar = ''.join(sorted(s))
    temp = s.replace(" ","")
    max = None
    maxchar = None
    for alph in allchar.lower():
        charcount = temp.count(alph)
        if alph not in string.ascii_letters: continue
        elif charcount > max:
            max = charcount
            max = alph
        elif charcount == max:
            max2 = charcount            
            max2 = alph
            max.append(max2)
    return max

如果我输入'aaaabbbb',它应该给我'ab',但它只给我'a'。我该如何解决这个问题?

最佳答案

您可以使用内置 collections.Counter :

from collections import Counter

def most_frequent_letter(s):
    counter = Counter(s)
    letter, max_count = next(counter.most_common())
    letters = sorted(letter
                     for letter, count in counter.most_common()
                     if count == max_count)
    return ''.join(letters)

如果由于某种原因您无法使用Counter,您可以使用default dictionary :

from collections import defaultdict

def most_frequent_letter(s):
    counter = defaultdict(int)
    for char in s:
        counter[char] += 1
    max_count = max(counter.values())
    letters = sorted(letter
                     for letter, count in counter.items()
                     if count == max_count)
    return ''.join(letters)

关于python - python 字符串中出现频率最高的一个或多个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31329411/

相关文章:

python - 使用 python 的多处理池和映射函数测量进度

在多维数组上使用 Realloc 和 strcat 时缺少字符?

string - 无法理解寄存器和变量之间的汇编mov指令

Java 字符串数组插入排序

python - 无法从 Docker 连接到数据库

python 文档测试和协程

python - 在 amazon ec2 或 picloud 中并行运行相同的 python 脚本涉及哪些步骤

arrays - 将字符串 append 到 Matlab 数组

c# - 如何修剪字符串中的前导逗号

python - 时间戳以秒为单位返回日期时间的年份