Random Word List Generator and Text Word Count

  • Share this:

Code introduction


This function accepts a text and a language parameter, then generates a random word list and counts the number of words in the given text.


Technology Stack : Typer, random, string, collections.Counter

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_word_count(text, language="en"):
    """
    Count the number of words in the given text and return the count.
    """
    import random
    import string
    from collections import Counter

    # Generate a random word list based on the specified language
    if language == "en":
        word_list = random.choices(string.ascii_lowercase, k=1000)
        word_list = ''.join(word_list)
    elif language == "es":
        word_list = random.choices(string.ascii_lowercase + "áéíóúüñ", k=1000)
        word_list = ''.join(word_list)
    else:
        raise ValueError("Unsupported language")

    # Count the occurrences of each word in the generated list
    word_counts = Counter(word_list)
    
    # Return the word count for the given text
    return len(text.split())