16 Dec 2022

Use Python for Sentiment Analysis

Here’s an example of how you could use the Natural Language Toolkit (NLTK) to perform sentiment analysis on a list of quotes about a specific subject:

import nltk

# Download required resources from NLTK
nltk.download('vader_lexicon')
nltk.download('averaged_perceptron_tagger')

# Define a list of quotes about a specific subject
quotes = [
    "I love the way this product works!",
    "This product is great for what I need",
    "I'm so happy with this purchase",
    "This product is a game-changer",
    "I'm not a fan of this product",
    "I'm disappointed with the performance of this product",
    "I wouldn't recommend this product to a friend",
    "I'm returning this product, it's not what I expected"
]

# Use NLTK's built-in sentiment analyzer to classify the sentiment of each quote
from nltk.sentiment.vader import SentimentIntensityAnalyzer

sia = SentimentIntensityAnalyzer()

for quote in quotes:
    sentiment = sia.polarity_scores(quote)
    print(f'{quote}: {sentiment}')

This code will print out the sentiment scores for each quote, with scores ranging from -1 (most negative) to 1 (most positive). You can then use these scores to determine the overall sentiment towards the specific subject being discussed in the quotes.

Alternatively, you can use the TextBlob library to perform sentiment analysis in a similar way. Here’s an example using TextBlob:

import textblob

# Define a list of quotes about a specific subject
quotes = [ "I love the way this product works!",
           "This product is great for what I need",
           "I'm so happy with this purchase",
           "This product is a game-changer",
           "I'm not a fan of this product",
           "I'm disappointed with the performance of this product",
           "I wouldn't recommend this product to a friend",
           "I'm returning this product, it's not what I expected"]

# Use TextBlob to classify the sentiment of each quote
for quote in quotes:
    sentiment = textblob.TextBlob(quote).sentiment
    print(f'{quote}: {sentiment}')