Python program to count the frequency of each words in a string

Python program to count the frequency of each words in a string :

In this python tutorial,we will learn how to count the frequency of each words in a user input string. The program will read all words , find out the number of occurrence for each words and print them out. It also sorts all the words alphabetically .
To solve this problem , we will use one dictionary. Dictionaries can store key-value pairs. For this dictionary, key will the words of the string and value will be the frequency for that word. For the string “hello world hello” , it will look like below :

key - hello , value - 2
key - world , value - 1

It will print the value of world before hello i.e. alphabetically. Let’s take a look at the program first :

Python program :

input_line = input("Enter a string : ")

words_dict = {}

for word in input_line.split():
		words_dict[word] = words_dict.get(word,0) + 1

for key in sorted(words_dict):
	print("{} : {}".format(key,words_dict[key])) 

Explanation :

The commented numbers in the above program denote the step-number below :

1. Ask the user to enter a string . Read and store it in input_line variable.
2. Create one dictionary to store the key-value pair , where key is the word and value is the frequency of that word.
3. Start scanning one by one word of the string. Read the current frequency value for that word from the dictionary and add 1 to it or increment it by 1. If the current frequency is not available, return 0.
4. Sort all keys of the dictionary alphabetically. That means, sort all words contains in the dictionary alphabetically. Also print out the value of the frequency and word .

Sample Output :

Enter a string : hello hello world
hello : 2
world : 1

Enter a string : this is a line with multiple words with repeated words
a : 1
is : 1
line : 1
multiple : 1
repeated : 1
this : 1
with : 2
words : 2

Leave a Reply