Sentiment Analysis with Flair Text Classifier

  • Share this:

Code introduction


This function uses a pre-trained text classifier from the Flair library to perform sentiment analysis on the given text and returns the predicted sentiment category.


Technology Stack : Flair, TextClassifier, Sentence

Code Type : Text classification

Code Difficulty : Intermediate


                
                    
def random_entity_recognition(text):
    from flair.models import TextClassifier
    from flair.data import Sentence
    
    # Load a pre-trained text classifier
    classifier = TextClassifier.load('en-sentiment')
    
    # Create a sentence object
    sentence = Sentence(text)
    
    # Predict the sentiment of the text
    classifier.predict(sentence)
    
    # Return the predicted sentiment
    return sentence.labels[0].value