Text Analysis: Frequency and Average Word Length

  • Share this:

Code introduction


This function takes a text string as input, counts and returns the five most common words and their frequencies in the text, as well as calculates and returns the average word length.


Technology Stack : collections.Counter, statistics.mean

Code Type : Analyze text

Code Difficulty : Intermediate


                
                    
import random
from collections import Counter
from statistics import mean

def analyze_text_frequency(text):
    # This function analyzes the frequency of each word in a given text and returns the most common words.
    words = text.split()
    word_counts = Counter(words)
    most_common_words = word_counts.most_common(5)
    average_word_length = mean(len(word) for word in words)
    
    return most_common_words, average_word_length