Random Word Generation with Sentiment Classification Using Flair

  • Share this:

Code introduction


This function uses the Flair library to generate a specified number of random words and classify each word's sentiment. It first initializes a tokenizer and a text classifier, then generates random words and classifies each one.


Technology Stack : Flair, Tokenizer, TextClassifier

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def random_word_generator(num_words, word_length):
    import random
    import flair
    from flair.tokenization import Tokenizer
    from flair.models import TextClassifier

    # Initialize tokenizer and text classifier
    tokenizer = Tokenizer()
    text_classifier = TextClassifier.load('en')

    # Generate random words
    random_words = []
    for _ in range(num_words):
        random_text = ' '.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=word_length))
        random_words.append(random_text)

    # Classify the random words
    classified_words = []
    for word in random_words:
        word_tokens = tokenizer.tokenize(word)
        prediction = text_classifier.predict(word_tokens)
        classified_words.append({
            'word': word,
            'category': prediction.label
        })

    return classified_words