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. Show With CounterThe 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. ExampleLive 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) OutputRunning the above code gives us the following result − OutputGiven 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. ExampleLive 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) OutputRunning 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 setA 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. ExampleLive 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) OutputRunning 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}
Updated on 05-May-2020 10:23:52
In this python program, we will be Calculating the Frequency of a character in a string or how many times a character is present in a string. The string is a datatype in programing language and is formed when 2 or more characters join or concatenate together. Now it is not necessary for a string to have a distinct character, it can be meaningless or meaningful can have distinct characters or can be a combination of the same characters. Method 1This method is the most naive method –
Run string = "Yolo Life" for i in string: frequency = string.count(i) print(str(i) + ": " + str(frequency), end=", ") OutputY: 1, o: 2, l: 1, o: 2, : 1, L: 1, i: 1, f: 1, e: 1, Method 2This method uses a dictionary in python.
Run str = "YOLO LIFE" # create dictionary to store key value pair dict = {} for i in str: # if i already appears as key in dict, increment the count if i in dict: dict[i] += 1 # else i appears for the first time, add to dict else: dict[i] = 1 # printing result print(dict) Output{'Y': 1, 'O': 2, 'L': 2, ' ': 1, 'I': 1, 'F': 1, 'E': 1} Method 3 (Using Counter)This method uses a counter from collections Run from collections import Counter string = "Yolo Life" output = Counter(string) print(output) OutputCounter({'o': 2, 'Y': 1, 'l': 1, ' ': 1, 'L': 1, 'i': 1, 'f': 1, 'e': 1}) Method 4 Using Set() and Count()This method is better than the previous method that used count as we are converting the string into a set of unique items. So, Loop will not run for duplicate items and only for unique items in the set() Run string = "aabbbccccdddddeeeeee" # using set() reduces string "YOLO LIFE" with 20 items # to a set of 5 items : {'a', 'b', 'c', 'd', 'e'} # now print count each item in set appearing in string # storing result as dictionary # for loop runs only 5 times res = {i: string.count(i) for i in set(string)} print(res) Output{'a': 2, 'c': 4, 'b': 3, 'e': 6, 'd': 5} Method 5 Using dict.get()The Run string = "YOLO LIFE" res = {} for key in string: # if item doesn't exist res.get(key, 0) returns 0 as result # we use res.get(key, 0) + 1 so as to initialize value as 1 on first occurrence # if item exits then res.get(key, 0) + 1 just increments the previously held value res[key] = res.get(key, 0) + 1 # printing result print (res) Output{'Y': 1, 'O': 2, 'L': 2, ' ': 1, 'I': 1, 'F': 1, 'E': 1} Note Time Complexity: O(n), where n is the number of characters in the string.
How do you find the frequency of each character in a string?Python. string = "picture perfect";. freq = [None] * len(string);. for i in range(0, len(string)):. freq[i] = 1;. for j in range(i+1, len(string)):. if(string[i] == string[j]):. freq[i] = freq[i] + 1;. #Set string[j] to 0 to avoid printing visited character.. How do you count the frequency of words in a string in Python?Use set() method to remove a duplicate and to give a set of unique words. Iterate over the set and use count function (i.e. string. count(newstring[iteration])) to find the frequency of word at each iteration.
How do you find the frequency of each element in a list in Python?We are going to use a module method to find the frequency of elements.. Import the collections module.. Initialize the list with elements.. Get the frequency of elements using Counter from collections module.. Convert the result to dictionary using dict and print the frequency.. |