Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 输入为';句子';,如何返回显示最频繁的元素_Python_Python 3.x - Fatal编程技术网

Python 输入为';句子';,如何返回显示最频繁的元素

Python 输入为';句子';,如何返回显示最频繁的元素,python,python-3.x,Python,Python 3.x,第一个函数计算字符串的字符数 def character_count(sentence): characters = {} for char in sentence: if char in characters: characters[char] = characters[char] + 1 else: characters[char] = 1 return characters 第二个函

第一个函数计算字符串的字符数

def character_count(sentence):
    characters = {}
    for char in sentence:
        if char in characters:
            characters[char] = characters[char] + 1
        else: 
            characters[char] = 1
    return characters
第二个函数确定最常见的字符,并通过在上一个helper函数中建立的字符[char]来标识最常出现的字符

def most_common_character(sentence):
    chars = character_count(sentence)
    most_common = ""
    max_times = 0


    for curr_char in chars:
        if chars[curr_char] > max_times:
            most_common = curr_char
            max_times = chars[curr_char]
    return most_common

你实际上不需要改变任何事情!您的代码将按原样使用列表(变量名只是会产生误导)。试试看:

输出:

'a'

这将适用于具有任何类型的可散列元素(数字、字符串、字符等)的列表。

为什么不简单地使用Python提供的内容呢

>>> from collections import Counter
>>> sentence = "This is such a beautiful day, isn't it"
>>> c = Counter(sentence).most_common(3)
>>> c
[(' ', 7), ('i', 5), ('s', 4)]
如果您真的想逐字进行并避免空格,请执行以下操作:

>>> from collections import Counter
>>> sentence = "This is such a beautiful day, isn't it"
>>> res = Counter(sentence.replace(' ', ''))
>>> res.most_common(1)
[('i', 5)]

目前什么是
句子
?字符串?只需使用
计数器
>>> from collections import Counter
>>> sentence = "This is such a beautiful day, isn't it"
>>> res = Counter(sentence.replace(' ', ''))
>>> res.most_common(1)
[('i', 5)]