360Studies

360 Studies.com Logo

Your Destination for Career Excellence in Bioscience, Statistics, and Data Science

Sentiment analysis using TextBlob, SentiWordNet, and VADER in Python

sentiment-analysis-using-textblob-sentiwordnet-and-vader-in-python

To perform sentiment analysis using TextBlob, SentiWordNet, and VADER in Python, you can use the following code. First, you need to install the required libraries if you haven’t already. You can install them using pip:

pip install textblob nltk

You’ll also need to download the NLTK data for SentiWordNet:

import nltk
nltk.download('sentiwordnet')
nltk.download('punkt')

Now, let’s perform sentiment analysis using TextBlob, SentiWordNet, and VADER for an artificially created sentence:

from textblob import TextBlob
from nltk.corpus import sentiwordnet as swn
from nltk.sentiment.vader import SentimentIntensityAnalyzer

# Sample sentence
sentence = "I love this beautiful and amazing place, but the service was terrible."

# Sentiment analysis using TextBlob
def analyze_with_textblob(text):
analysis = TextBlob(text)
sentiment = analysis.sentiment.polarity
if sentiment > 0:
return "Positive"
elif sentiment == 0:
return "Neutral"
else:
return "Negative"

# Sentiment analysis using SentiWordNet
def analyze_with_sentiwordnet(text):
sentiment = 0.0
tokens = nltk.word_tokenize(text)
for token in tokens:
synsets = list(swn.senti_synsets(token))
if synsets:
pos_score = synsets[0].pos_score()
neg_score = synsets[0].neg_score()
sentiment += pos_score - neg_score

if sentiment > 0:
return "Positive"
elif sentiment == 0:
return "Neutral"
else:
return "Negative"

# Sentiment analysis using VADER
def analyze_with_vader(text):
sia = SentimentIntensityAnalyzer()
sentiment = sia.polarity_scores(text)['compound']
if sentiment > 0.05:
return "Positive"
elif sentiment < -0.05:
return "Negative"
else:
return "Neutral"

# Perform sentiment analysis using all three methods
textblob_sentiment = analyze_with_textblob(sentence)
sentiwordnet_sentiment = analyze_with_sentiwordnet(sentence)
vader_sentiment = analyze_with_vader(sentence)

# Print results
print(f"TextBlob Sentiment: {textblob_sentiment}")
print(f"SentiWordNet Sentiment: {sentiwordnet_sentiment}")
print(f"VADER Sentiment: {vader_sentiment}")

This code defines three functions for sentiment analysis using TextBlob, SentiWordNet, and VADER, and then applies them to the sample sentence. Each method assigns a sentiment label (Positive, Neutral, or Negative) to the sentence based on its sentiment analysis.

Looking for latest updates and job news, join us on Facebook, WhatsApp, Telegram and Linkedin

You May Also Like

Scroll to Top