如何输出最常用的字母?

时间:2018-07-23 19:38:31

标签: python python-3.x

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

此代码输出字母并使用了多少次,但是我如何修改它以查找并打印最常用的字母?

4 个答案:

答案 0 :(得分:0)

您可以按值对字母进行排序,然后编写该排序数组的最后一个成员:

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

答案 1 :(得分:0)

因此,要从字典x中找到使用最多的单词,可以使用operator--

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

但这只会给您n个相等的单词(即最大值)中的一个

答案 2 :(得分:0)

如果您正在寻找一种易于阅读的解决方案,并且该解决方案很接近您想要实现的解决方案,那么可以解决问题,

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 != " ":,因为您的初始代码会将空格视为单词,这可能不是您想要的。

答案 3 :(得分:-1)

也许您想使用集合中的“ defaultdict()”     即使在字典中没有按键时,它所做的就是,     它不会导致任何错误

import collections
s = "This is a random sequence of text"
d = collections.defaultdict(int)
for c in s:
    if c != " ":
        d[c] += 1
print(sorted(d.items(), key=lambda x: x[1], reverse=True)[0])