用字典计算字母频率 [英] counting letter frequency with a dict

查看:122
本文介绍了用字典计算字母频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在没有计数器的情况下找到字母的频率,并且代码将输出结果的字典形式.到目前为止,我所做的是使程序对单词频率进行计数,而不对字母/字符频率进行计数.如果有人可以指出我在此代码中的错误,那将是很棒的.谢谢你. 它应该看起来像这样:

I'm trying to find the frequency of letters without the Counter.And the code will output a dictionary form of result. And what I have done so far is to make the program count the word frequencies but not the letter/character frequencies. If anyone could point out my mistakes in this code that would be wonderful. Thank you. It supposed to look like this:

{'a':2,'b':1,'c':1,'d':1,'z':1}

**但这是我真正得到的:

**but this is what I am actually getting:

{'abc':1,'az':1,'ed':1}

**我的代码在下面

word_list=['abc','az','ed']
def count_letter_frequency(word_list):
  letter_frequency={}
  for word in word_list:
    keys=letter_frequency.keys()
    if word in keys:
        letter_frequency[word]+=1
    else:
        letter_frequency[word]=1
  return letter_frequency

推荐答案

这是正确的代码:

word_list=['abc','az','ed']

def count_letter_frequency(word_list):
  letter_frequency={}
  for word in word_list:
    for letter in word:
      keys=letter_frequency.keys()
      if letter in keys:
          letter_frequency[letter]+=1
      else:
          letter_frequency[letter]=1
  return letter_frequency

您正在遍历列表,并且列表中包含单词.因此,您将单词作为字典中的键.因此,您必须添加另一个for循环来迭代每个单词中的字母.

You were iterating over the list and the list contains words. So, you were making words as keys in your dictionary. So, you have to add another for loop to iterate over the letters in each word.

这篇关于用字典计算字母频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆