TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Compute Frequency of Each Word in Python String
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python ExamplesPython Tutorials

Compute Frequency of Each Word in Python String

Last updated: Nov 05, 2023 12:09 am
By Meenakshi Agarwal
Share
5 Min Read
Count frequency of each word in a Python string
Count frequency of each word in a Python string
SHARE

This tutorial provides several techniques to count the frequency of each word in a Python string, followed by simple examples.

Contents
Using List to count the word frequency in a stringUsing Python set method to get the word frequency

Here, we have to write a Python program that will accept a string as input and calculate the occurrence of each word in it. We can address this problem with many programming logic. Let’s find out each solution one by one.

Python Program – Compute Frequency of Words in a String

It is always exciting to solve a problem by taking diverse approaches. A real programmer keeps trying and considers doing things in a better way.

Using List to count the word frequency in a string

Let’s see how can we use a list to count the occurrences of each word in a string. Following is the step by step detail:

  • The first thing, we’ll do it is to convert the string to a list. Python string has a split() method. It takes a string and some separator (actually a space in our case) to return a list.
  • Next, we’ll need to use another list that will be empty initially.
  • After that, we’ll store unique values of the first list into the second one.
  • Finally, we’ll use the Python range to iterate string list having unique values that mean inside a loop.
  • In the loop, the count() function will give us the count of each unique word present in the parent string.

See the full logic in the below coding snippet.

"""
Program:
 Python program to count frequency of each word in a string
"""
def get_word_freq(input_string): 

   # convert the input string into a list of words
   input_string_list = input_string.split()     
   
   print("*******************")
   print("input_string_list = ", input_string_list)
   print("*******************\n")
    
   unique_string_list = [] 

   # iterate the input string list and find unique words 
   for i in input_string_list:         

      # test for duplicate values 
      if i not in unique_string_list: 

         # add unique words to second list
         unique_string_list.append(i) 

   print("*******************")
   print("unique_string_list = ", unique_string_list)
   print("*******************\n")
   
   print("*******************")
   for i in range(0, len(unique_string_list)): 

      # compute word frequency in input string 
      print('Word Frequency [{}]: {}'.format(unique_string_list[i], input_string_list.count(unique_string_list[i])))
    
   print("*******************")

def Driver(): 
   input_string ='python csharp javascript php python javascript csharp python csharp php'
   get_word_freq(input_string)                

if __name__=="__main__": 
   Driver()          # call Driver() function 

The result of the above coding snippet is as follows:

*******************
input_string_list =  ['python', 'csharp', 'javascript', 'php', 'python', 'javascript', 'csharp', 'python', 'csharp', 'php']
*******************

*******************
unique_string_list =  ['python', 'csharp', 'javascript', 'php']
*******************

*******************
Word Frequency [python]: 3
Word Frequency [csharp]: 3
Word Frequency [javascript]: 2
Word Frequency [php]: 2
*******************

Sometimes, you might also need to convert a list to string, so have yourself go over it.

Using Python set method to get the word frequency

Subsequently, we can use Python’s set() function to compute the frequency of each word in a string. Given below are some high-level steps to accomplish the task.

  • Again, as in the first method, we did the splitting of the input string, here also, we have to do it.
  • After that, we’ll use the Python Set to remove the duplicates from the given string. In Python, the Set, by definition, has unique values and ignores the copies.
  • Finally, we’ll traverse over the set values and count the occurrences of each word.

See the full logic in the below coding snippet.

"""
Program:
 Python program to count frequency of each word in a string
"""
def get_word_freq(input_string): 

   # break the string into list of words 
   input_string_list = input_string.split() 

   # gives set of unique words 
   unique_string_set = set(input_string_list) 
   
   print("*******************")
   print("input_string_list = ", input_string_list)
   print("*******************\n")
    
   print("*******************")
   print("unique_string_set = ", unique_string_set)
   print("*******************\n")

   for entry in unique_string_set : 
      print('Frequency of ', entry , 'is :', input_string_list.count(entry)) 

# driver code 
if __name__ == "__main__": 
   
   input_string ='python csharp javascript php python javascript csharp python csharp php'
   
   # calling the freq function 
   get_word_freq(input_string) 

The result of the above coding snippet is as follows:

*******************
input_string_list =  ['python', 'csharp', 'javascript', 'php', 'python', 'javascript', 'csharp', 'python', 'csharp', 'php']
*******************

*******************
unique_string_set =  {'csharp', 'javascript', 'python', 'php'}
*******************

Frequency of  csharp is : 3
Frequency of  javascript is : 2
Frequency of  python is : 3
Frequency of  php is : 2

To learn more, read our flagship Python tutorial for beginners and advanced learners.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Count frequency of each character in a Python string Compute Frequency in Python String
Next Article Python lambda to find Palindromes and Anagrams in a list of strings Find Palindromes and Anagrams in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x