
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Find the k most frequent words from data set in Python
If there is a need to find 10 most frequent words in a data set, python can help us find it using the collections module. The collections module has a counter class which gives the count of the words after we supply a list of words to it. We also use the most_common method to find out the number of such words as needed by the program input.
Examples
In the below example we take a paragraph, and then first create a list of words applying split(). We will then apply the counter() to find the count of all the words. Finally the most_common function will give us the appropriate result of how many such words with highest frequency we want.
from collections import Counter word_set = " This is a series of strings to count " \ "many words . They sometime hurt and words sometime inspire "\ "Also sometime fewer words convey more meaning than a bag of words "\ "Be careful what you speak or what you write or even what you think of. "\ # Create list of all the words in the string word_list = word_set.split() # Get the count of each word. word_count = Counter(word_list) # Use most_common() method from Counter subclass print(word_count.most_common(3))
Output
Running the above code gives us the following result −
[('words', 4), ('sometime', 3), ('what', 3)]
- Related Articles
- Finding n most frequent words from a sentence in JavaScript
- Top K Frequent Words in C++
- Python Program to crawl a web page and get most frequent words
- Find most frequent element in a list in Python
- Find top K frequent elements from a list of tuples in Python
- Program to find frequency of the most frequent element in Python
- Python program to find Most Frequent Character in a String
- Top K Frequent Elements in Python
- How to find the most frequent factor value in an R data frame column?
- Find the second most frequent element in array JavaScript
- C# program to find the most frequent element
- Find Second most frequent character in array - JavaScript
- Python program for most frequent word in Strings List
- Program to find most frequent subtree sum of a binary tree in Python
- Find k longest words in given list in Python

Advertisements