Frequency of each character in String in Python



Text processing has emerged as an important field in machine learning and AI. Python supports this filed with many available tools and libraries. In this article we will see how we can find the number of occurrence of each letter of a given string.

With Counter

The Counter method counts the number of occurrences of an element in an iterable. So it is straight forward to use by passing the required string into it.

Example

 Live Demo

from collections import Counter

# Given string
strA = "timeofeffort"
print("Given String: ",strA)
# Using counter
res = {}

for keys in strA:
res[keys] = res.get(keys, 0) + 1

# Result
print("Frequency of each character :\n ",res)

Output

Running the above code gives us the following result −

Output

Given String: timeofeffort
Frequency of each character :
{'t': 2, 'i': 1, 'm': 1, 'e': 2, 'o': 2, 'f': 3, 'r': 1}

With get()

We can treat the string as a dictionary and count the keys for each character using get() in a for loop.

Example

 Live Demo

# Given string
strA = "timeofeffort"
print("Given String: ",strA)
# Using counter
res = {}

for keys in strA:
res[keys] = res.get(keys, 0) + 1

# Result
print("Frequency of each character :\n ",res)

Output

Running the above code gives us the following result −

Given String: timeofeffort
Frequency of each character :
{'t': 2, 'i': 1, 'm': 1, 'e': 2, 'o': 2, 'f': 3, 'r': 1}

With set

A set in python stores unique elements. So we can use it wisely by counting the number of times the same character is encountered again and again when looping through the string as an iterable.

Example

 Live Demo

# Given string
strA = "timeofeffort"
print("Given String: ",strA)
# Using counter
res = {}

res={n: strA.count(n) for n in set(strA)}

# Result
print("Frequency of each character :\n ",res)

Output

Running the above code gives us the following result −

Given String: timeofeffort
Frequency of each character :
{'f': 3, 'r': 1, 'm': 1, 'o': 2, 'i': 1, 't': 2, 'e': 2}

Advertisements