Open In App

Find frequency of each word in a string in Python

Last Updated : 20 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.


Output

Frequency 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


Output

Frequency 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(): 

  1. Split the string into a list containing the words by using split function (i.e. string.split()) in python with delimiter space. 
  2. Use set() method to remove a duplicate and to give a set of unique words 
  3. 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)


Output

Frequency 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.


Output

Frequency 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)


Output

Frequency 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


Output

apple : 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


Output

Frequency 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

Calculate the frequency of each word in the given string
Given a string str, the task is to find the frequency of each word in a string. Examples: Input: str = "Geeks For Geeks" Output: For 1 Geeks 2 Explanation: For occurs 1 time and Geeks occurs 2 times in the given string str. Input: str = "learning to code is learning to create and innovate" Output: and 1 code 1 create 1 innovate 1 is 1 learning 2 to
6 min read
Generate a number such that the frequency of each digit is digit times the frequency in given number
Given a number N containing digits from 1 to 9 only. The task is to generate a new number using the number N such that the frequency of each digit in the new number is equal to the frequency of that digit in N multiplied by the digit itself.Note: The digits in the new number must be in increasing order.Examples: Input : N = 312 Output : 122333 Expl
8 min read
Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
Given a string S, the task is to find the prefix of string S with the maximum possible length such that frequency of each character in the prefix is at most the number of characters in S with minimum frequency. Examples: Input: S = 'aabcdaab' Output: aabcd Explanation: Frequency of characters in the given string - {a: 4, b: 2, c: 1, d: 1} Minimum f
8 min read
Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
Given two strings, the task is to check whether the frequencies of a character(for each character) in one string are multiple or a factor in another string. If it is, then output "YES", otherwise output "NO". Examples: Input: s1 = "aabccd", s2 = "bbbaaaacc" Output: YES Frequency of 'a' in s1 and s2 are 2 and 4 respectively, and 2 is a factor of 4 F
6 min read
Python Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”
4 min read
Find the Frequency of a Particular Word in a Cell in an Excel Table in Python
In this article, we'll look at how to use Python to find the number of times a word appears in a cell of an Excel file. Before we begin with the steps of the solution, the following modules/libraries must be installed. We will use the following sample Excel file to determine the frequency of the input words. Dataset Used It can be downloaded from h
5 min read
C program to find and replace a word in a File by another given word
Pre-requisite: File Handling in CGiven a file containing some text, and two strings wordToBeFind and wordToBeReplacedWith, the task is to find all occurrences of the given word 'wordToBeFind' in the file and replace them with the given word ‘wordToBeReplacedWith’. Examples: Input : File = "xxforxx xx for xx", wordToBeFind = "xx", wordToBeReplacedWi
3 min read
Find the word from a given sentence having given word as prefix
Given a string S representing a sentence and another string word, the task is to find the word from S which has the string word as a prefix. If no such word is present in the string, print -1. Examples: Input: S = "Welcome to Geeksforgeeks", word="Gee"Output: GeeksforgeeksExplanation:The word "Geeksforgeeks" in the sentence has the prefix "Gee". In
8 min read
Java Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”
5 min read
Javascript Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap" Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks
3 min read
Practice Tags :
three90RightbarBannerImg