You can download this code by clicking the button below.
This code is now available for download.
This function uses a pre-trained text classifier from the Flair library to predict the sentiment (positive, negative, or neutral) of the given text.
Technology Stack : Flair (Text Analysis Library)
Code Type : Text Classification
Code Difficulty : Intermediate
import random
from flair.models import TextClassifier
from flair.data import Sentence
from flair.tokenization import Tokenizer
def predict_sentiment(text):
# Load a pre-trained text classifier for sentiment analysis
classifier = TextClassifier.load('en-sentiment')
# Create a sentence from the input text
sentence = Sentence(text, tokenization=Tokenizer('en'))
# Predict the sentiment of the sentence
classifier.predict(sentence)
# Return the sentiment and confidence
return sentence.labels[0].value, sentence.labels[0].score