python - 找到单词中最常见的字母;按字母顺序

标签 python python-3.x dictionary

程序输入是一个字符串。我想要从这个字符串中找到最常见的字母。如果有多个字母具有相同的频率,我将返回拉丁字母表中第一个字母

代码:

def most_Wanted(text="Hello Oman"):
    lst = [x for x in text.replace(" ","").lower() if x.isalpha]
    count = {}
    for letter in lst:
        if letter in count:
            count[letter] += 1
        else:
            count[letter] = 1
    count = list(count.items())
    sorted(count, key=lambda x: (-x[1],x[0]))
    print(count[0][0])

预期:

l #though o and l appear 3 times, l is before o in the latin alphabet

输出:

h #there seems to be an error in the sorting as the first pair of tuples in the list always seems to be the first letter of the text?

任何关于美化代码的建议都很好,尽管我宁愿现在不使用模块,这样我就可以学习核心Python。谢谢:)

最佳答案

主要问题是 sorted 返回一个新列表,它不是就地的。

您应该重新分配其返回值,或使用.sort():

count = sorted(count, key=lambda x: (-x[1],x[0]))

count.sort(key=lambda x: (-x[1],x[0]))


线路也有问题

lst = [x for x in text.replace(" ","").lower() if x.isalpha]

if x.isalpha 总是返回 True 因为它只是引用函数而不是实际调用它。应改为

lst = [x for x in text.replace(" ","").lower() if x.isalpha()]

关于python - 找到单词中最常见的字母;按字母顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47845635/

相关文章:

python - Keras 连接形状 [(1, 8), (None, 32)]

python - 如何将 '1,1'形式的字符串转换为float(1,1)?

python - 合并两个可能不相等的具有少量结构的列表

python-3.x - Python - 按月和日绘制多个数据帧(忽略年份)

python - 防止在 QStyledItemDelegate 中编辑 ComboBox

python - 如何修复 Mac 上与 Xvfb 和 selenium 相关的 'Program install error'?

python - 如何获得路径的正确大写?

python - 如何使用权重将字典合并在一起?

java - 解析可变行数

python - 根据另一列填写空单元格