Python program to count number of occurrences of each word in string

Spread the love

In this tutorial, you will learn how to write a python program to count number of occurrences of each word in string. This is one of the step in text pre- processing. This step will help in data preparation for building models for machine leaning.

str_1 = 'Hi, How are you ? I am fine, What about you ?' def count_words(str): counts = {} words = str.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts print(count_words(str_1))

Output:

{'Hi,': 1, 'How': 1, 'are': 1, 'you': 2, '?': 2, 'I': 1, 'am': 1, 'fine,': 1, 'What': 1, 'about': 1}

 

admin

admin

Leave a Reply

Your email address will not be published. Required fields are marked *