AI-based Sentiment Analysis Python, NLP

👤 Sharing: AI
```python
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import re

nltk.download('vader_lexicon')  # Download the VADER lexicon if you haven't already
nltk.download('punkt')

class SentimentAnalyzer:
    """
    A class for performing sentiment analysis on text using NLTK's VADER.
    """

    def __init__(self):
        """
        Initializes the SentimentAnalyzer with VADER sentiment intensity analyzer.
        """
        self.analyzer = SentimentIntensityAnalyzer()

    def clean_text(self, text):
        """
        Cleans the input text by removing special characters and extra spaces.

        Args:
            text (str): The input text to clean.

        Returns:
            str: The cleaned text.
        """
        text = re.sub(r'[^a-zA-Z\s]', '', text)  # Remove special characters
        text = re.sub(r'\s+', ' ', text).strip()  # Remove extra spaces
        return text


    def analyze_sentiment(self, text):
        """
        Analyzes the sentiment of the given text using VADER.

        Args:
            text (str): The text to analyze.

        Returns:
            dict: A dictionary containing the sentiment scores (positive, negative, neutral, compound).
        """
        cleaned_text = self.clean_text(text)
        scores = self.analyzer.polarity_scores(cleaned_text)
        return scores

    def get_sentiment_label(self, text, threshold=0.05):
        """
        Gets the sentiment label (positive, negative, or neutral) based on the compound score.

        Args:
            text (str): The text to analyze.
            threshold (float): The threshold for determining positive/negative sentiment.

        Returns:
            str: The sentiment label ('positive', 'negative', or 'neutral').
        """
        scores = self.analyze_sentiment(text)
        compound_score = scores['compound']

        if compound_score >= threshold:
            return 'positive'
        elif compound_score <= -threshold:
            return 'negative'
        else:
            return 'neutral'



if __name__ == '__main__':
    analyzer = SentimentAnalyzer()

    text1 = "This is a great and amazing product! I love it."
    text2 = "This is terrible. I hate it so much!"
    text3 = "This is okay. It's not bad, but not great either."
    text4 = "The weather is just alright today."
    text5 = "I am extremely happy and excited!"

    print(f"Text: {text1}")
    sentiment_scores1 = analyzer.analyze_sentiment(text1)
    print(f"Sentiment Scores: {sentiment_scores1}")
    sentiment_label1 = analyzer.get_sentiment_label(text1)
    print(f"Sentiment Label: {sentiment_label1}\n")

    print(f"Text: {text2}")
    sentiment_scores2 = analyzer.analyze_sentiment(text2)
    print(f"Sentiment Scores: {sentiment_scores2}")
    sentiment_label2 = analyzer.get_sentiment_label(text2)
    print(f"Sentiment Label: {sentiment_label2}\n")

    print(f"Text: {text3}")
    sentiment_scores3 = analyzer.analyze_sentiment(text3)
    print(f"Sentiment Scores: {sentiment_scores3}")
    sentiment_label3 = analyzer.get_sentiment_label(text3)
    print(f"Sentiment Label: {sentiment_label3}\n")

    print(f"Text: {text4}")
    sentiment_scores4 = analyzer.analyze_sentiment(text4)
    print(f"Sentiment Scores: {sentiment_scores4}")
    sentiment_label4 = analyzer.get_sentiment_label(text4)
    print(f"Sentiment Label: {sentiment_label4}\n")

    print(f"Text: {text5}")
    sentiment_scores5 = analyzer.analyze_sentiment(text5)
    print(f"Sentiment Scores: {sentiment_scores5}")
    sentiment_label5 = analyzer.get_sentiment_label(text5)
    print(f"Sentiment Label: {sentiment_label5}\n")
```
👁️ Viewed: 12

Comments