Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting Letter Frequency in a String (Python) [duplicate]

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

word = input("Enter a word")

Alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

for i in range(0,26):
    print(word.count(Alphabet[i]))

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?

word="Hello"

H 1

E 1

L 2

O 1

like image 318
Kelvin San Avatar asked Dec 05 '16 23:12

Kelvin San


People also ask

How do you count duplicate letters in a string in Python?

Step 1: Declare a String and store it in a variable. Step 2: Use 2 loops to find the duplicate characters. Outer loop will be used to select a character and initialize variable count to 1. Step 3: Inner loop will be used to compare the selected character with remaining characters of the string.

How do you count the number of repeated strings in a string in Python?

Python has a built-in function for counting the repeated substring in a given string called count(). As the name suggests, it counts the occurrence of a substring in a given string.


Video Answer


2 Answers

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

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.

like image 188
LMc Avatar answered Sep 21 '22 17:09

LMc


def char_frequency(str1):
    dict = {}
    for n in str1:
        keys = dict.keys()
        if n in keys:
            dict[n] += 1
        else:
            dict[n] = 1
    return dict
print(char_frequency('google.com'))
like image 30
Uzam Hashmi Avatar answered Sep 18 '22 17:09

Uzam Hashmi