Random Word Generation with Polyglot Library

  • Share this:

Code introduction


The function takes a string (source) and a language code (language) as input, and uses the Text class from the Polyglot library to generate a random word. It first downloads the necessary models for the specified language, and then randomly selects a word from the text.


Technology Stack : polyglot, Text, downloader

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_word_generator(source, language='en'):
    """
    Generates a random word based on the provided source and language.
    """
    from polyglot.text import Text
    from polyglot.downloader import downloader

    # Download necessary models for the given language
    downloader.download('embeddings2.en')
    text = Text(source, hint_language_code=language)
    
    # Generate a random word from the text
    random_word = text.random_word()
    
    return random_word