counting letter frequency with a dict

瘦欲@ 提交于 2019-12-13 10:35:08

问题


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}

**my code is below

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

回答1:


This is the correct code:

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

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.




回答2:


Use collections.Counter

from collections import Counter

print Counter(''.join(word_list))
# Counter({'a': 2, 'c': 1, 'b': 1, 'e': 1, 'd': 1, 'z': 1})

Or count the elements yourself if you don't want to use Counter.

from collections import defaultdict

d = defaultdict(int)
for c in ''.join(word_list):
    d[c] += 1
print d
# defaultdict(<type 'int'>, {'a': 2, 'c': 1, 'b': 1, 'e': 1, 'd': 1, 'z': 1})



回答3:


Would this be acceptable:

flat = ''.join(word_list)
{l: flat.count(l) for l in set(flat)}
#{'a': 2, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'z': 1}

If you would prefer this in for loop, here it goes:

flat = ''.join(word_list)
result = {}
for l in flat:
    if l in result:
        result[l] += 1
    else:
        result[l] = 1


来源:https://stackoverflow.com/questions/46486462/counting-letter-frequency-with-a-dict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!