Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

python 3.x - counting letter frequency with a dict

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...