×

Word frequency Python

Word frequency Python

In this tutorial, we will write the Python program to count the occurrence of a word (word frequency) in a given sentence. We will learn all the approaches which we are going to use to write such a program. In the output of the program, the user will get the word frequency for each word used in the sentence.

Example::

"An apple a day keeps the doctor away but doctor should also eat an apple every day."

In the above-given sentence:

  • An occurred two times
  • Apple occurred two times
  • A occurred only one time
  • Doctor occurred two times
  • Day also occurred two times, etc.

So, we can see that that's how the occurrence of the words or word frequency from a sentence is counted.

We will write a program where we will get the frequency of each word present in the sentence in the way mentioned above as an output of it. We will use the following approaches in our program to get the word frequency in the output:

1). Using the Python list approach

2). Using Python set approach

3). Using the Python dictionary approach

Let's learn about all these approaches in detail and write a Python program with each of them.

Method 1: Using Python list:

In this method, we will follow the following steps for developing a Python program to get the word frequency in the output:

Step 1: We will get the sentence or set of words as string type from the user in the input form.

Step 2: We will split the words of the given string into a list by using string.split() function on the string with delimiter space.

Step 3: Now, we will initialize an empty list in the program.

Step 4: After that, if any word is not present in the new empty list that we have initialized then, we will append the word from the given string.

Step 5: We will use iteration on the new list and then use the count () function.

Step 6: We will print the frequency of each word in the output by the print statement.

Now, let's understand the implementation of these steps or approach by using them in the following program:

Example – 

 # Define a default function for word frequency
 def worfreq (String):
 # Break the string into a list of words using string.split () function
 String = String.split ()
 NewList = [] # initializing an empty list
 # Using for loops till all the given values in string
 for j in String:
 # Checking the duplicity using empty list
 if j not in NewList:
 # Appending values in the empty list
 NewList.append (j)
 # Iterating over the new list
 for j in range (0, len (NewList)):
 # Using count () function and printing result in the output
 print ('Frequency of', NewList [j], 'word is :', String.count (NewList [j]))
 def main ():
         # Taking sentence as user input
 mkr = input ("Enter your input sentence: ")
 worfreq (mkr) # calling out default function
 if __name__=="__main__":
 main () # calling the main function 

Output:

 Enter your input sentence: An apple is mango but mango is not an apple
 Frequency of An word is : 2
 Frequency of apple word is : 2
 Frequency of is word is : 2
 Frequency of mango word is : 2
 Frequency of but word is : 1
 Frequency of not word is : 1 

As we can see in the output, we have got word frequency for every word that we have given in the sentence as the user input in the program.

Method 2: Using Python set

In the Python set approach, we will use to store the collection of unique words from the sentence provided in the program. We will use the following steps in this method to write the program:

Step 1: As the first method, here we will also take the sentence in string form as user input and split the words from the given sentence using string.split() function with delimiter space.

Step 2: Now, we will use the set() function to remove all the duplicate or multiple occurred words from the sentence and store the unique words inside the sentence.

Step 3: After that, we will iterate over the defined set of unique words and use the count () function to get the word frequency.

Step 4: We will use the print statement to print the word frequency as a result in output.

Let's understand this method by implementing the above steps in the following example program:

Example – 

 # Define a default function for word frequency
 def worfreq (String):
     # Break the given string into a list of words using string.split () function
     NewList = String.split ()
     # Defining a set for unique words of the sentence
     UqWords = set (NewList)
     # Iterating over the set of unique words 
     for words in UqWords :
         # Using count () function for word frequency
         print ('Frequency of ', words , 'word is:', NewList.count (words)) # printing result in output
 def main ():
         # Taking sentence as user input
 mkr = input ("Enter your input sentence: ")
 worfreq (mkr) # calling out default function
 if __name__=="__main__":
 main () # calling the main function 

Output:

 Enter your input sentence: An apple is mango but mango is not An apple
 Frequency of but word is: 1
 Frequency of apple word is: 2
 Frequency of not word is: 1
 Frequency of is word is: 2
 Frequency of An word is: 2
 Frequency of mango word is: 2 

Method 3: Using Python dictionary

In this method, we will use the Python dictionary and its functions to get the word frequency from a given sentence. Now, let's understand the implementation of this approach by using it in the following program:

Example – 

 # Define a default function for word frequency
 def count (elemen):
 # Checking if words in the sentence have '.' at last and if so then we will ignore it
 if elemen [-1] == '.':
 elemen = elemen [0:len (elemen) - 1]
 # Using dictionary keys for checking duplicity in given sentence
 if elemen in dictation:
 dictation [elemen] += 1
 # Defining elements inside the empty dictionary
 else:
 dictation.update ({elemen: 1})
 # Taking sentence as user input
 mkr = input ("Enter your input sentence: ")
 # Define an empty dictionary
 dictation = {}
 # Splitting all words of the given string using string.split ()
 NewList = mkr.split ()
 # Counting each word from string using count function
 for elemen in NewList:
 count (elemen)
 # Getting the word frequency as key values from new dictionary 
 for AllKey in dictation: # iterating over keys from dictionary
 print ("Frequency of ", AllKey, "word is", end = " ")
 print (":", end = " ")
 print (dictation [AllKey], end = " ") # printing result in output
 print () 

Output:

 Enter your input sentence: An apple is mango but mango is not An apple
 Frequency of An word is : 2 
 Frequency of apple word is : 2 
 Frequency of is word is : 2 
 Frequency of mango word is : 2 
 Frequency of but word is : 1 
 Frequency of not word is : 1 

Explanation – 

As we can see in the output, we have got word frequency for each word that is present in the sentence that we gave as the user input in the program. So, that’s how we can use the dictionary approach in a Python program to get the word frequency.


Related Topics

Python MySQL Update Operation

Python MySQL Update Operation: In this part of tutorial, we will learn that how can we update a table present in SQL database through our Python program. As like SQL,...

4 minutes read.

Run exec python from PHP

PHP (which is a recursive abbreviation for PHP Hypertext Preprocessor) is one of the most broadly involved web improvement innovations on the planet. PHP code utilized for creating sites and...

4 minutes read.

Python Set difference() Method

Python Set difference() Method The set.difference() method in Python returns the set difference of two sets(A-B). Syntax set.difference(set1) Parameter set- This argument represents a set (minuend) set1- This arguments represents a set(subtrahend) Return This method returns the difference of the two specified...

2 minutes read.

Python oct() function

Python oct() function The oct() function in Python converts an integer number to an octal string prefixed with “0o”. Syntax oct(x) Parameter x: This parameter represents an Integer Number Return This function returns an octal string. Example 1 #...

1 minute read.

Python Set symmetric_difference() method

Python Set symmetric_difference() method The set.symmetric_difference() method returns a new set, which is the symmetric difference of two sets. The returned set contains only the unique items and, hence, deleting the common elements of...

2 minutes read.

Python If-else statement

In real life, there are situations where we have to make decisions for a particular circumstance and based on those decisions, and we plan our next move. The same thing...

4 minutes read.

Assignment Operators in Python

The prime usage of Assignment Operators is to assign values to variables. These are taken into account to do operations on values and variables. There are some special symbols in python...

4 minutes read.

How to Concat two Dataframes in Python

Using Pandas dataframe, we can concat two dataframes or series in Python. So let's take a brief introduction to what is Pandas in Python. Pandas is a library typically used for...

7 minutes read.

How to reverse a string in Python

In Python language, we have a few ways to reverse a string. In this article, let us discuss these ways and understand the suitability of these ways in different scenarios...

5 minutes read.

Python String isupper() method

Python String isupper() method The String.isupper() method in Python returns a boolean value ‘true’ if all cased characters in the string are uppercase else for any other value is returns false. Syntax String.isupper() Parameter NA Return This...

2 minutes read.

chr() and ord() Functions in Python

Python language contains many built-in functions which we use for many programs to work efficiently. The chr() and ord() are a few built-in functions in Python that are used for...

4 minutes read.

Android apps for coding in python

Nowadays, it is the generation of smartphones. The world can be seen and acknowledged with a single click on your mobile phone. Everyone uses mobile phones to do any work,...

9 minutes read.

Artificial intelligence mini projects with source code in Python

Project Name: Movie recommendation system A recommendation provides customers with relevant information related to their searches. Before the recommendation system, the most common method of purchasing was to rely on the...

4 minutes read.

Python Bubble Sort

Bubble sort is one of the techniques used to sort the elements in lists in a certain order, either in ascending or descending order. It is called Bubble sort because...

4 minutes read.

Convert string into int in Python

String A string is defined as a series of characters, special characters, and numbers. A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements...

2 minutes read.

Python filter() function

Python filter() function The filter() function constructs an iterator from those elements of iterable for which the parameter ‘function’ returns a Boolean value true. Syntax filter(function, iterable) Parameter function: This parameter represents a function to be run for each item in the...

1 minute read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.

Append key Value to Dictionary in Python

The Python dictionary is one of the built-in data types. Elements of dictionaries are key-value pairs. In Python, there are numerous ways to add dictionaries. Let's examine some of the...

9 minutes read.

How to Open a file in python with Path

In this tutorial, we will see rather than the traditional way of opening a file by locating or navigating it from our desktops; we will learn how to open the...

2 minutes read.

Captcha Code in Python with Example

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.