Random Word Selection Based on Frequency

  • Share this:

Code introduction


This function takes an input text and a language code as arguments, first counts the frequency of each word in the input text, and then randomly selects and returns a word based on these frequencies.


Technology Stack : Lingua library's word_frequency and random_word functions

Code Type : Function

Code Difficulty : Intermediate


                
                    
def generate_random_word_count(input_text, language="en"):
    from lingua import word_frequency
    from lingua import random_word

    # Count the frequency of each word in the input text
    word_counts = word_frequency(input_text, language=language)

    # Generate a random word based on its frequency
    random_word_result = random_word(word_counts)

    return random_word_result