如何输出最常用的字母?

2024-04-25 13:52:20 发布

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

def main():
    x = {}
    for word in sentence: 
        x[word] = sentence.count(word)
    for letter in sorted(x):
        print (letter + ': ' + str(x[letter]))


sentence=input("Enter a sentence: ")
main()

这段代码输出了字母和它被使用了多少次,但是我如何修改它来找到和打印最常用的字母呢?你知道吗


Tags: 代码inforinputmaindefcount字母
3条回答

只需按值对字母排序,然后写入排序数组的最后一个成员:

def main():
    x = {}
    for word in sentence:
        x[word] = sentence.count(word)

    sorted_letters = sorted(x, key=lambda v: x[v])
    for letter in sorted_letters:
        print (letter + ': ' + str(x[letter]))

    print('Most used letter =', sorted_letters[-1])


sentence=input("Enter a sentence: ")
main()

样本输入/输出:

Enter a sentence: Hello World!
H: 1
e: 1
 : 1
W: 1
r: 1
d: 1
!: 1
o: 2
l: 3
Most used letter = l

因此,要从dict x中找到最大使用量的单词,可以使用operator,比如-

import operator
print max(x.iteritems(), key=operator.itemgetter(1))[0]

但这只会给你n个单词中有一个相等的,即最大值

如果你正在寻找一个易于阅读的解决方案,接近你想要实现的,那就可以了

def main():
    x = {}
    for word in sentence:
        if word != " ": 
            x[word] = sentence.count(word)
    maximum_occurrences = max(x.values())
    for letter,occurrences in x.items():
         if occurrences == maximum_occurrences:
              print("Max value found, the letter "+ letter + " was found " + str(occurrences)+ " times.")

sentence=input("Enter a sentence: ")
main()

>>>> Enter a sentence:  This is simply a test
>>>> Max value found, the letter s was found 4 times.

基本上,它返回任何出现次数最多的字母。请注意,这会处理多个字母出现次数相同的情况。你知道吗

编辑

另外请注意,我添加了if word != " ":,因为您的初始代码将空格视为可能不是您想要的单词。你知道吗

相关问题 更多 >