Word Frequency Analysis Function

  • Share this:

Code introduction


This function takes a string parameter 'text', counts the frequency of each word in the text, and returns a list of words and their frequencies sorted in descending order of frequency.


Technology Stack : collections.Counter, string splitting

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
from collections import Counter

def analyze_text_frequency(text):
    # Count the frequency of each word in the text
    word_counts = Counter(text.split())
    # Sort the words by frequency
    sorted_word_counts = sorted(word_counts.items(), key=lambda item: item[1], reverse=True)
    return sorted_word_counts