Counting Letter Frequency in a String (Python)

Posted on

Question :

Counting Letter Frequency in a String (Python)

I am trying to count the occurrences of each letter of a word

word = input("Enter a word")


for i in range(0,26):

This currently outputs the number of times each letter occurs including the ones that don’t.

How do I list the letters vertically with the frequency alongside it, e.g., like the following?


H 1

E 1

L 2

O 1

Answer #1:

from collections import Counter
counts=Counter(word) # Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})
for i in word:

Try using Counter, which will create a dictionary that contains the frequencies of all items in a collection.

Otherwise, you could do a condition on your current code to print only if word.count(Alphabet[i]) is greater than 0, though that would be slower.

Answered By: LMc

Answer #2:

def char_frequency(str1):
    dict = {}
    for n in str1:
        keys = dict.keys()
        if n in keys:
            dict[n] += 1
            dict[n] = 1
    return dict
Answered By: Uzam Hashmi

Answer #3:

As Pythonista said, this is a job for collections.Counter:

from collections import Counter
print(Counter('cats on wheels'))

This prints:

{'s': 2, ' ': 2, 'e': 2, 't': 1, 'n': 1, 'l': 1, 'a': 1, 'c': 1, 'w': 1, 'h': 1, 'o': 1}
Answered By: duhaime

Answer #4:

s = input()
t = s.lower()

for i in range(len(s)):
    b = t.count(t[i])
    print("{} -- {}".format(s[i], b))
Answered By: Swetank

Answer #5:

Following up what LMc said, your code was already pretty close to functional. You just needed to post-process the result set to remove ‘uninteresting’ output. Here’s one way to make your code work:

#!/usr/bin/env python
word = raw_input("Enter a word: ")

Alphabet = [

hits = [
    (Alphabet[i], word.count(Alphabet[i]))
    for i in range(len(Alphabet))
    if word.count(Alphabet[i])

for letter, frequency in hits:
    print letter.upper(), frequency

But the solution using collections.Counter is much more elegant/Pythonic.

Answered By: evadeflow

Answer #6:

An easy and simple solution without a library:

string = input()
f = {}
for i in string:
  f[i] = f.get(i,0) + 1

Here is the link for get():

Answered By: soheshdoshi

Answer #7:

If using libraries or built-in functions is to be avoided then the following code may help:

s = "aaabbc"  # Sample string
dict_counter = {}  # Empty dict for holding characters
                   # as keys and count as values
for char in s:  # Traversing the whole string
                # character by character
    if not dict_counter or char not in dict_counter.keys(): # Checking whether the dict is
                                                            # empty or contains the character
        dict_counter.update({char: 1}) # If not then adding the
                                       # character to dict with count = 1
    elif char in dict_counter.keys(): # If the character is already
                                      # in the dict then update count
        dict_counter[char] += 1
for key, val in dict_counter.items(): # Looping over each key and
                                      # value pair for printing
    print(key, val)


a 3
b 2
c 1

Answer #8:

For future references: When you have a list with all the words you want, lets say wordlistit’s pretty simple

for numbers in range(len(wordlist)):
    if wordlist[numbers][0] == 'a':
Answered By: Stanley

Leave a Reply

Your email address will not be published.