我有一个问题,在哪里需要字典,并尝试查找字母的每个实例(如果存在)并将其打印出来

 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:

10-06 14:01
查看更多