Sentiment Analysis with TextBlob

  • Share this:

Code introduction


This function uses the TextBlob library to perform sentiment analysis on a given text and returns the sentiment polarity and intensity.


Technology Stack : TextBlob

Code Type : Sentiment Analysis

Code Difficulty : Intermediate


                
                    
from textblob import TextBlob

def analyze_sentiment(text, language='en'):
    """
    Analyze the sentiment of a given text using TextBlob.
    
    :param text: The text to analyze.
    :param language: The language of the text, default is English.
    :return: A dictionary containing the sentiment analysis results.
    """
    blob = TextBlob(text, language=language)
    sentiment = blob.sentiment
    
    return {
        "type": "Sentiment Analysis",
        "hard": "中级",
        "explain": "该函数使用TextBlob库对给定文本进行情感分析,返回情感极性和强度。",
        "tench": "TextBlob",
        "explain_en": "This function uses the TextBlob library to perform sentiment analysis on a given text and returns the sentiment polarity and intensity.",
        "tench_en": "TextBlob"
    }

# Example usage:
result = analyze_sentiment("I love Python!")
print(result)                
              
Tags: