Skip to main content
 首页 » 编程设计

python之一个字母在字典中出现了多少次

2025年05月04日10shihaiming

我有一个问题,它需要一个字典并尝试找到一个字母的每个实例(如果它存在)并打印它

 get_letter_frequency('all animals are equal but some animals are more equal than others') 

将打印:

a appears 10 times 
b appears 1 time 
e appears 7 times 
h appears 2 times 
i appears 2 times 
l appears 6 times 
m appears 4 times 
n appears 3 times 
o appears 3 times 
q appears 2 times 
r appears 4 times 
s appears 4 times 
t appears 3 times 
u appears 3 times 

到目前为止,我的 get_letter_frequency 函数已经有了这个

def get_letter_frequency(a_string): 
    dictionary = {} 
    words = a_string.split() 
    for letters in words: 
      if letters != " ": 
          if letters in dictionary: 
              dictionary[letters] += 1 
          else: 
              dictionary[letters] = 1 
      dictionary_keys = dictionary.keys() 
      new_list = list(dictionary_keys) 
      new_list.sort() 
      for alphabet in new_list: 
          if dictionary[alphabet] == 1: 
              print(alphabet, "appears", dictionary[alphabet], "time") 
          else: 
              print(alphabet, "appears", dictionary[alphabet], "times") 

但这反而给了我字典中的所有字母,并告诉我它出现了多少次。

all appears 1 time 
animals appears 2 times 
are appears 2 times 
but appears 1 time 
equal appears 2 times 
more appears 1 time 
others appears 1 time 
some appears 1 time 
than appears 1 time 

你能帮忙吗?谢谢。

请您参考如下方法:

错误在这些行中:

words = a_string.split() 
for letters in words: 

您期望它遍历 words 中的所有字母,但它实际上遍历了单个单词。在 Python 中,您可以将字符串当作字符的 list 来使用,因此将 `for 行更改为以下行将起作用:

for letters in a_string: