Counting letter occurances Python

给你一囗甜甜゛ 提交于 2019-12-01 09:11:16

问题


I am trying to count letter occurances and print them. This is what i have so far:

def histogram(L):
    d = {}
    for x in L:
      for letter in x:
        if letter in d:
          d[letter] += 1
        else:
          d[letter] = 1
    for i in range(len(d)):
      print('{} | {}'.format(d, d[i])) # GETTING ERRORS ON THIS LINE
    return d
histogram(open('cipher.txt'))

For some reason i am getting errors on that line. How would i print it correctly?

EDIT:solution my Martijn! Props! but does anyone know how to sort the dictionary by alphabetical order?


回答1:


d is a dictionary, not a list. Loop over the keys:

for key in d:
    print('{} | {}'.format(key, d[key]))

or you'll get KeyError exceptions.

You may be interested in the collections.Counter() class; it's a counting dictionary:

from collections import Counter

def histogram(L):
    d = Counter(letter for line in L for letter in x)
    for letter in d:
        print('{} | {}'.format(letter, d[letter]))
    return d



回答2:


Just for fun, lets simplify your code. You can use a set() on the initial string to get a list of the unique characters, then just use the count method of the list.

def histogram(L):
    d = {letter:L.count(letter) for letter in set(L)}
    for key in d:
        print "{} | {}".format(key, d[key]}


来源:https://stackoverflow.com/questions/18630101/counting-letter-occurances-python

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