You can download this code by clicking the button below.
This code is now available for download.
This function uses a pre-trained sentiment analysis model from the Flair library to analyze the sentiment of a given text and returns the sentiment label (positive, negative, or neutral) of the text.
Technology Stack : Flair, TextClassifier, Sentence
Code Type : Function
Code Difficulty : Intermediate
def flair_random_sentiment_analysis(text, language='en'):
"""
Perform sentiment analysis on a given text using Flair's pre-trained model.
Args:
text (str): The text to analyze.
language (str): The language of the text. Default is 'en' for English.
Returns:
str: The sentiment of the text ('positive', 'negative', 'neutral').
"""
from flair.models import TextClassifier
from flair.data import Sentence
# Load pre-trained sentiment analysis model
classifier = TextClassifier.load('en-sentiment')
# Create a Sentence object
sentence = Sentence(text)
# Perform sentiment analysis
classifier.predict(sentence)
# Return the sentiment of the text
return sentence.labels[0].value