Frequency of each word in string python

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.count(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

def freq(str):

    str = str.split()        

    str2 = []

    for i in str:            

        if i not in str2:

            str2.append(i)

    for i in range(0, len(str2)):

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

Output

Frequency of apple is : 3
Frequency of mango is : 3
Frequency of orange is : 2
Frequency of guava is : 1

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

def freq(str):

    str_list = str.split()

    unique_words = set(str_list)

    for words in unique_words :

        print('Frequency of ', words , 'is :', str_list.count(words))

if __name__ == "__main__":

    str ='apple mango apple orange orange apple guava mango mango'

    freq(str)

Output

Frequency of  guava is : 1
Frequency of  orange is : 2
Frequency of  mango is : 3
Frequency of  apple is : 3

Approach 3 (Using Dictionary):

Python3

def count(elements):

    if elements[-1] == '.':

        elements = elements[0:len(elements) - 1]

    if elements in dictionary:

        dictionary[elements] += 1

    else:

        dictionary.update({elements: 1})

Sentence = "Apple Mango Orange Mango Guava Guava Mango"

dictionary = {}

lst = Sentence.split()

for elements in lst:

    count(elements)

for allKeys in dictionary:

    print ("Frequency of ", allKeys, end = " ")

    print (":", end = " ")

    print (dictionary[allKeys], end = " ")

    print()

Output

Frequency of  Apple : 1 
Frequency of  Mango : 3 
Frequency of  Orange : 1 
Frequency of  Guava : 2 


How do you count the frequency of a word 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 a word in a string?

Use a Map data structure to store the occurrence of each word in the string. Traverse the entire string and check whether the current word is present in map or not. If it is present, then update the frequency of the current word else insert the word with frequency 1.

How do you count the frequency of each character in a string in Python?

count() coupled with set() can also achieve this task, in this we just iterate over the set converted string and get the count of each character in original string and assign that element with that value counted using count() .

How do you count repeated words in a text file in Python?

Python Count Unique Words in Text File.
create a counter and assign default value as zero..
open a file in read only mode..
read the data of file..
split the data in words and store it in a set..
start a for loop and keep on incrementing the counter with each word..
Ultimately, print the counter..