Random Positive Sentiment Word Generator

  • Share this:

Code introduction


The function generates a specified number of random words, which are selected to be positive sentiment. It uses the TextClassifier from the Flair library to classify the generated words.


Technology Stack : Flair, TextClassifier, Sentence

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_word_generator(num_words, word_length):
    import random
    import flair
    from flair.models import TextClassifier
    from flair.data import Sentence
    
    # Load a pre-trained text classifier
    classifier = TextClassifier.load('en-sentiment')
    
    # Generate random words
    random_words = []
    for _ in range(num_words):
        while True:
            # Generate a random word of specified length
            word = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=word_length))
            # Check if the generated word is a positive sentiment
            sentence = Sentence(word)
            classifier.predict(sentence)
            if sentence.labels[0].value == 'POSITIVE':
                random_words.append(word)
                break
    
    return random_words