Find frequency of each word in a string in Python
Last Updated :
20 Feb, 2023
Write a python code to find the frequency of each word in a given string. Examples:
Input : str[] = "Apple Mango Orange Mango Guava Guava Mango"
Output : frequency of Apple is : 1
frequency of Mango is : 3
frequency of Orange is : 1
frequency of Guava is : 2
Input : str = "Train Bus Bus Train Taxi Aeroplane Taxi Bus"
Output : frequency of Train is : 2
frequency of Bus is : 3
frequency of Taxi is : 2
frequency of Aeroplane is : 1
Approach 1 using list():
1. Split the string into a list containing the words by using split function (i.e. string.split()) in python with delimiter space.
Note:
string_name.split(separator) method is used to split the string
by specified separator(delimiter) into the list.
If delimiter is not provided then white space is a separator.
For example:
CODE : str='This is my book'
str.split()
OUTPUT : ['This', 'is', 'my', 'book']
2. Initialize a new empty list.
3. Now append the word to the new list from previous string if that word is not present in the new list.
4. Iterate over the new list and use count function (i.e. string.
Python3
# Find frequency of each word in a string in Python
# using dictionary.
def count(elements):
# check if each word has '.' at its last. If so then ignore '.'
if elements[-1] == '.':
elements = elements[0:len(elements) - 1]
# if there exists a key as "elements" then simply
# increase its value.
if elements in dictionary:
dictionary[elements] += 1
# if the dictionary does not have the key as "elements"
# then create a key "elements" and assign its value to 1.
else:
dictionary.update({elements: 1})
# driver input to check the program.
Sentence = "Apple Mango Orange Mango Guava Guava Mango"
# Declare a dictionary
dictionary = {}
# split all the word of the string.
lst = Sentence.split()
# take each word from lst and pass it to the method count.
for elements in lst:
count(elements)
# print the keys and its corresponding values.
for allKeys in dictionary:
print ("Frequency of ", allKeys, end = " ")
print (":", end = " ")
print (dictionary[allKeys], end = " ")
print()
# This code is contributed by Ronit Shrivastava.
OutputFrequency of Apple : 1
Frequency of Mango : 3
Frequency of Orange : 1
Frequency of Guava : 2
Time complexity : O(n)
Space complexity : O(n)
(newstring[iteration])) to find the frequency of word at each iteration.
Note:
string_name.count(substring) is used to find no. of occurrence of
substring in a given string.
For example:
CODE : str='Apple Mango Apple'
str.count('Apple')
str2='Apple'
str.count(str2)
OUTPUT : 2
2
Implementation:
Python3
# Python code to find frequency of each word
def freq(str):
# break the string into list of words
str = str.split()
str2 = []
# loop till string values present in list str
for i in str:
# checking for the duplicacy
if i not in str2:
# insert value in str2
str2.append(i)
for i in range(0, len(str2)):
# count the frequency of each word(present
# in str2) in str and print
print('Frequency of', str2[i], 'is :', str.count(str2[i]))
def main():
str ='apple mango apple orange orange apple guava mango mango'
freq(str)
if __name__=="__main__":
main() # call main function
OutputFrequency of apple is : 3
Frequency of mango is : 3
Frequency of orange is : 2
Frequency of guava is : 1
Time complexity : O(n^2)
Space complexity : O(n)
Approach 2 using set():
- Split the string into a list containing the words by using split function (i.e. string.split()) in python with delimiter space.
- 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.
Implementation:
Python3
# Python3 code to find frequency of each word
# function for calculating the frequency
def freq(str):
# break the string into list of words
str_list = str.split()
# gives set of unique words
unique_words = set(str_list)
for words in unique_words :
print('Frequency of ', words , 'is :', str_list.count(words))
# driver code
if __name__ == "__main__":
str ='apple mango apple orange orange apple guava mango mango'
# calling the freq function
freq(str)
OutputFrequency of orange is : 2
Frequency of mango is : 3
Frequency of guava is : 1
Frequency of apple is : 3
Time complexity : O(n^2)
Space complexity : O(n)
Approach 3 (Using Dictionary):
Python3
# Find frequency of each word in a string in Python
# using dictionary.
def count(elements):
# check if each word has '.' at its last. If so then ignore '.'
if elements[-1] == '.':
elements = elements[0:len(elements) - 1]
# if there exists a key as "elements" then simply
# increase its value.
if elements in dictionary:
dictionary[elements] += 1
# if the dictionary does not have the key as "elements"
# then create a key "elements" and assign its value to 1.
else:
dictionary.update({elements: 1})
# driver input to check the program.
Sentence = "Apple Mango Orange Mango Guava Guava Mango"
# Declare a dictionary
dictionary = {}
# split all the word of the string.
lst = Sentence.split()
# take each word from lst and pass it to the method count.
for elements in lst:
count(elements)
# print the keys and its corresponding values.
for allKeys in dictionary:
print ("Frequency of ", allKeys, end = " ")
print (":", end = " ")
print (dictionary[allKeys], end = " ")
print()
# This code is contributed by Ronit Shrivastava.
OutputFrequency of Apple : 1
Frequency of Mango : 3
Frequency of Orange : 1
Frequency of Guava : 2
time complexity : O(m * n)
space complexity : O(k)
Approach 4: Using Counter() function:
Python3
# Python3 code to find frequency of each word
# function for calculating the frequency
from collections import Counter
def freq(str):
# break the string into list of words
str_list = str.split()
frequency = Counter(str_list)
for word in frequency:
print('Frequency of ', word, 'is :', frequency[word])
# driver code
if __name__ == "__main__":
str = 'apple mango apple orange orange apple guava mango mango'
# calling the freq function
freq(str)
OutputFrequency of apple is : 3
Frequency of mango is : 3
Frequency of orange is : 2
Frequency of guava is : 1
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach 4 (Using setdefault):
Python3
# Python3 code to find frequency of each word
def freq(str):
# break the string into list of words
str_list = str.split()
# create an empty dictionary
frequency = {}
# count frequency of each word
for word in str_list:
frequency[word] = frequency.setdefault(word, 0) + 1
# print the frequency of each word
for key, value in frequency.items():
print(key, ':', value)
str = 'apple mango apple orange orange apple guava mango mango'
# calling the function
freq(str)
#This code is contributed by Edula Vinay Kumar Reddy
Outputapple : 3
mango : 3
orange : 2
guava : 1
Time Complexity: O(n), where n is the length of the given string
Auxiliary Space: O(n)
Approach 5 :Using operator.countOf() method:
Python3
import operator as op
# Python code to find frequency of each word
def freq(str):
# break the string into list of words
str = str.split()
str2 = []
# loop till string values present in list str
for i in str:
# checking for the duplicacy
if i not in str2:
# insert value in str2
str2.append(i)
for i in range(0, len(str2)):
# count the frequency of each word(present
# in str2) in str and print
print('Frequency of', str2[i], 'is :', op.countOf(str,str2[i]))
def main():
str ='apple mango apple orange orange apple guava mango mango'
freq(str)
if __name__=="__main__":
main() # call main function
OutputFrequency of apple is : 3
Frequency of mango is : 3
Frequency of orange is : 2
Frequency of guava is : 1
Time Complexity: O(N), where n is the length of the given string
Auxiliary Space: O(N)
Similar Reads
Python - Find all close matches of input string from a list In Python, there are multiple ways to find all close matches of a given input string from a list of strings. Using startswith() startswith() function is used to identify close matches for the input string. It checks if either the strings in the list start with the input or if the input starts with t
3 min read
Convert string to a list in Python Our task is to Convert string to a list in Python. Whether we need to break a string into characters or words, there are multiple efficient methods to achieve this. In this article, we'll explore these conversion techniques with simple examples. The most common way to convert a string into a list is
2 min read
Find the first repeated word in a string in Python using Dictionary We are given a string that may contain repeated words and the task is to find the first word that appears more than once. For example, in the string "Learn code learn fast", the word "learn" is the first repeated word. Let's understand different approaches to solve this problem using a dictionary. U
3 min read
Reverse each word in a sentence in Python In this article, we will explore various methods to reverse each word in a sentence. The simplest approach is by using a loop.Using LoopsWe can simply use a loop (for loop) to reverse each word in a sentence.Pythons = "Hello World" # Split 's' into words words = s.split() # Reverse each word using a
2 min read
Possible Words using given characters in Python Given a dictionary and a character array, print all valid words that are possible using characters from the array. Note: Repetitions of characters is not allowed. Examples: Input : Dict = ["go","bat","me","eat","goal","boy", "run"] arr = ['e','o','b', 'a','m','g', 'l'] Output : go, me, goal. This pr
5 min read
numpy string operations | find() function numpy.core.defchararray.find(arr, sub, start=0, end=None) is another function for doing string operations in numpy.It returns the lowest index in the string where substring sub is found for each element in arr within the range start to end.It returns -1 otherwise. Parameters: arr : array_like of str
2 min read
Python - Check if substring present in string The task is to check if a specific substring is present within a larger string. Python offers several methods to perform this check, from simple string methods to more advanced techniques. In this article, we'll explore these different methods to efficiently perform this check.Using in operatorThis
2 min read
Python | Words extraction from set of characters using dictionary Given the words, the task is to extract different words from a set of characters using the defined dictionary. Approach: Python in its language defines an inbuilt module enchant which handles certain operations related to words. In the approach mentioned, following methods are used. check() : It che
3 min read
Python - Separate first word from String We need to write a Python program to split a given string into two parts at the KáµÊ° occurrence of a specified character. If the character occurs fewer than K times, return the entire string as the first part and an empty string as the second part. Separating the first word from a string involves ide
2 min read
Python - Replace all occurrences of a substring in a string Replacing all occurrences of a substring in a string means identifying every instance of a specific sequence of characters within a string and substituting it with another sequence of characters. Using replace()replace () method is the most straightforward and efficient way to replace all occurrence
2 min read