Implementing sentiment analysis
The user wants a Python program for sentiment analysis using NLTK. They likely need code and a brief explanation. They may prefer a simple implementation with VADER for its ease of use. I should write it to take text input and output sentiment scores. I’ll include necessary installation instructions and Python script details, using nltk.sentiment.vader for the SentimentIntensityAnalyzer. A CLI-based approach works best, so I’ll provide options for analyzing a single string or reading from a file. Let’s get crafting!Building the sentiment analysis program
I need to include key pieces for the sentiment analysis program. First, I’ll mention that the user should install NLTK with pip install nltk and download the 'vader_lexicon'. Then, I’ll show how to import it and initialize the SentimentIntensityAnalyzer. I’ll create the analyze_sentiment function that classifies scores based on a compound value with given thresholds for positive, negative, and neutral sentiments. While I could mention training a classifier with the movie_reviews corpus, the VADER method is simpler and more appropriate for this task. I want to present this in markdown format with a standalone script and a brief Jupyter example. Let’s finalize that! Below is a complete, minimal Python program that performs sentiment analysis using NLTK’s VADER sentiment analyzer (which is designed for social media / general English text).
1. Install dependencies
pip install nltk
Then, in Python (only once), download the VADER lexicon:
import nltk
nltk.download('vader_lexicon')
2. Standalone sentiment analysis script
Save this as sentiment_analysis.py:
import nltk
from nltk.sentiment import SentimentIntensityAnalyzer
# Make sure the VADER lexicon is available.
# If you've never downloaded it before, uncomment the next two lines:
# import nltk
# nltk.download('vader_lexicon')
def analyze_sentiment(text: str) -> dict:
"""
Analyze the sentiment of a piece of text using NLTK's VADER.
Returns a dictionary with:
- 'neg': negative score
- 'neu': neutral score
- 'pos': positive score
- 'compound': overall score (-1 very negative, +1 very positive)
- 'label': 'positive', 'negative', or 'neutral'
"""
sia = SentimentIntensityAnalyzer()
scores = sia.polarity_scores(text)
compound = scores['compound']
# Standard VADER thresholds
if compound >= 0.05:
label = 'positive'
elif compound <= -0.05:
label = 'negative'
else:
label = 'neutral'
scores['label'] = label
return scores
def main():
print("Simple Sentiment Analyzer using NLTK VADER")
print("Type 'quit' or 'exit' to stop.\n")
while True:
text = input("Enter text: ").strip()
if text.lower() in {"quit", "exit"}:
break
if not text:
continue
result = analyze_sentiment(text)
print(f"\nSentiment scores: {result}")
print(f"Overall sentiment: {result['label']}\n")
if __name__ == "__main__":
main()
3. Run the program
python sentiment_analysis.py
Example interaction:
Simple Sentiment Analyzer using NLTK VADER
Type 'quit' or 'exit' to stop.
Enter text: I love this product, it works perfectly!
Sentiment scores: {'neg': 0.0, 'neu': 0.439, 'pos': 0.561, 'compound': 0.875, 'label': 'positive'}
Overall sentiment: positive
Enter text: This is the worst experience I've ever had.
Sentiment scores: {'neg': 0.499, 'neu': 0.501, 'pos': 0.0, 'compound': -0.8074, 'label': 'negative'}
Overall sentiment: negative
If you want a version that reads from a file or processes a list of sentences, I can adapt the code accordingly.