Python Counting Words Occurrences

By | April 1, 2020

Topic: Counting Words Occurrences in String Python Program

Counting Words Occurrences in String Python Program

 

# Python Program to input a string
# and find number of occurrences of
# each word in the given string
# using a user defined function

# define a user defined function
# that will receive a string as an argument
# will return a dictionary containing
# words and number of occurrences

def word_count_in_string(str):
    word_counts = dict()
    words = str.split()

    for word in words:
        if word in word_counts:
            word_counts[word] += 1
        else:
            word_counts[word] = 1

    return word_counts

str1 = input("Enter a string to find number of occurrences of each word:\n")
print( word_count_in_string(str1))

Output:
Enter a string to find number of occurrences of each word:
Python programs Java programs C programs C++ programs
{‘Python’: 1, ‘programs’: 4, ‘Java’: 1, ‘C’: 1, ‘C++’: 1}

Counting Words Occurrences in String Python Program

How This program works?

In this Python program we use the concept of dictionary in Python programming language. The dictionary will store the words of the string as well as respective count of each word.

We can say that every entry in the dictionary named word_count will be in (word,count) form.

First of all we define a user defined function named count_words_in_string(str) with a string argument str.

  • We will input the string at runtime.
  • This string will be passed to the user defined function.
  • The user defined function will create an empty dictionary.
  • The split() method of the string will split its words into a list called words.
  • That is, we will use for loop to count number of occurrencs of each word in the given string.
  • We will use a for loop to go through the list of words named words
    and when ever we find a word we will add 1 to ints count.
  • Hence by printing the dictionary, we will show each words with corresponding count.

One thought on “Python Counting Words Occurrences

  1. Pingback: Python Text File Program To Count Vowels | EasyCodeBook.com

Leave a Reply

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