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
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.
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.
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.
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With