字典不会按要求显示

问题描述

我需要解决一个练习(对于初学者!)并获得给定文本中所有出现字符的频率。我的问题是我被我试图编写的函数卡住了,因为我得到的是一个列表而不是字典。我知道问题可能出在“[]”的使用中,但我还没有找到任何更好的解决方案来获得至少一个结果。

这是我正在努力解决的问题:

def character_frequency(text):
"""
Returns the frequences of all occuring characters in the given text
:param text: A text
:return: Dict in the form {"<character>": frequency,"<character>": frequency,...}
"""

frequency = {}  # empty dict

    for line in text:
    for character in line.lower():
        if character in frequency:
            frequency[character] += 1
        else:
            frequency[character] = 1
            print(f"character{str(frequency)}")

return frequency

print()
print("excerise")
frequency = character_frequency(growing_plants)
for c,n in frequency.items():
    print(f"Character: {c}: {n}")

我应该如何更改我的函数以获得正确的字典结果?

解决方法

def character_frequency(text):
    """
    Returns the frequences of all occuring characters in the given text
    :param text: A text
    :return: Dict in the form {"<character>": frequency,"<character>": frequency,...}
    """

    frequency = {}  # empty dict

    for line in text:
        for character in line.lower():
            if character in frequency:
                frequency[character] += 1
            else:
                frequency[character] = 1

    return frequency

growing_plants = "Returns the frequences of all occuring characters in the given text"
print()
print("excerise")
frequency = character_frequency(growing_plants)
print(frequency)
# for c,n in frequency.items():
#     print(f"Character: {c}: {n}")

输出:

{'r': 6,'e': 9,'t': 6,'u': 3,'n': 5,'s': 3,' ': 10,'h': 3,'f': 2,'q': 1,'c': 5,'o': 2,'a': 3,'l': 2,'i': 3,'g': 2,'v': 1,'x': 1}
,

首先,我注意到你的缩进是错误的。

def character_frequency(text):
"""
Returns the frequences of all occuring characters in the given text
:param text: A text
:return: Dict in the form {"<character>": frequency,...}
"""
# Finding most occuring character

# Set frequency as empty dictionary
frequency_dict = {}

for character in string:
    if character in frequency_dict:
        frequency_dict[character] += 1
    else:
        frequency_dict[character] = 1

most_occurring = max(frequency_dict,key=frequency_dict.get)

# Displaying result
print("\nMost occuring character is: ",most_occuring)
print("It is repeated %d times" %(frequency_dict[most_occurring]))