Introduction
Sentiment analysis turns text into numbers — and a dashboard makes those numbers actionable. This post builds a live sentiment dashboard in Streamlit: paste text, get scores, see trends, and visualize word clouds. No ML training required.
Setup
pip install streamlit textblob vaderSentiment wordcloud matplotlib pandas
python -m textblob.download_corpora
Step 1: Sentiment scoring functions
from textblob import TextBlob
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
vader = SentimentIntensityAnalyzer()
def score_textblob(text):
blob = TextBlob(text)
return blob.sentiment.polarity # -1 to +1
def score_vader(text):
scores = vader.polarity_scores(text)
return scores["compound"] # -1 to +1
def label(score):
if score > 0.05: return "Positive"
if score < -0.05: return "Negative"
return "Neutral"
TextBlob is simpler and rule-based. VADER handles social media text (emojis, slang, caps) better. Use both and compare.
Step 2: KPI cards
import streamlit as st
st.title("📊 Sentiment Dashboard")
text = st.text_area("Paste text to analyze", height=150)
if text:
tb = score_textblob(text)
vd = score_vader(text)
avg = (tb + vd) / 2
c1, c2, c3, c4 = st.columns(4)
c1.metric("TextBlob", f"{tb:+.2f}", label(tb))
c2.metric("VADER", f"{vd:+.2f}", label(vd))
c3.metric("Average", f"{avg:+.2f}", label(avg))
c4.metric("Words", len(text.split()))
Step 3: Sentence-level breakdown
from textblob import TextBlob
blob = TextBlob(text)
sentences = blob.sentences
rows = []
for s in sentences:
rows.append({"Sentence": str(s), "Score": round(s.sentiment.polarity, 3), "Label": label(s.sentiment.polarity)})
import pandas as pd
df = pd.DataFrame(rows)
st.dataframe(df, use_container_width=True)
See which sentences are positive/negative — great for long reviews or articles.
Step 4: Word cloud
from wordcloud import WordCloud
import matplotlib.pyplot as plt
if text:
wc = WordCloud(width=800, height=400, background_color="white",
colormap="RdYlGn").generate(text)
fig, ax = plt.subplots(figsize=(10, 5))
ax.imshow(wc, interpolation="bilinear")
ax.axis("off")
st.pyplot(fig)
Word size = frequency. Color = sentiment (green = positive words, red = negative).
Step 5: Trend chart (multiple texts)
import pandas as pd
import plotly.express as px
if "history" not in st.session_state:
st.session_state.history = []
if text and st.button("Analyze & Add to Trend"):
st.session_state.history.append({
"text": text[:50] + "...",
"textblob": score_textblob(text),
"vader": score_vader(text),
"label": label((score_textblob(text) + score_vader(text)) / 2),
})
if st.session_state.history:
df = pd.DataFrame(st.session_state.history)
fig = px.line(df, y=["textblob", "vader"], title="Sentiment Trend",
labels={"value": "Score", "variable": "Method"})
fig.add_hline(y=0, line_dash="dash", line_color="gray")
st.plotly_chart(fig, use_container_width=True)
st.dataframe(df, use_container_width=True)
Track sentiment across multiple inputs — useful for monitoring reviews, social media, or support tickets.
Step 6: Batch analysis from CSV
uploaded = st.file_uploader("Upload CSV with a 'text' column", type="csv")
if uploaded:
df = pd.read_csv(uploaded)
df["textblob"] = df["text"].apply(score_textblob)
df["vader"] = df["text"].apply(score_vader)
df["label"] = df["vader"].apply(label)
st.dataframe(df, use_container_width=True)
# Distribution
counts = df["label"].value_counts()
fig = px.pie(values=counts.values, names=counts.index, title="Sentiment Distribution")
st.plotly_chart(fig, use_container_width=True)
# Download results
csv = df.to_csv(index=False).encode("utf-8")
st.download_button("📥 Download results", data=csv, file_name="sentiment_results.csv")
Upload a CSV of reviews/tweets, get scores for all, download the results.
Step 7: Real-time stream analysis
@st.fragment(run_every=2)
def live_feed():
# Simulate incoming messages
import random
msg = random.choice([
"I love this product!",
"Terrible experience, never again.",
"It's okay, nothing special.",
"Amazing quality, fast shipping!",
])
score = score_vader(msg)
st.write(f"**{msg}** → {score:+.2f} ({label(score)})")
live_feed()
Simulate a live feed of messages with real-time scoring. Replace the random choice with a real data source (API, DB, WebSocket).
Common mistakes
- Not handling empty text — TextBlob on empty string returns 0.0 (neutral). Check
if text.strip(). - Ignoring context — “not bad” scores negative with naive methods. VADER handles negation better.
- No normalization — scores range -1 to +1 but distributions vary. Normalize per-dataset for fair comparison.
- Over-relying on lexicon methods — TextBlob/VADER are rule-based. For production, use a trained model (Hugging Face, OpenAI).
- Word cloud on tiny text — needs 20+ words for a meaningful cloud.
Key Concepts
- Sentiment polarity = -1 (negative) to +1 (positive)
- TextBlob = simple rule-based sentiment
- VADER = handles social media text (emojis, slang, caps)
- Word cloud = visual frequency of words
- Batch processing = score many texts at once
What to Try Next
- Swap TextBlob/VADER for a Hugging Face model (
cardiffnlp/twitter-roberta-base-sentiment) for better accuracy. - Add aspect-based sentiment — score specific aspects (“battery life is great but screen is dim”).
- Combine with Streamlit real-time dashboard for live monitoring.
- Store results in Supabase for historical tracking.
FAQ
TextBlob vs VADER vs transformer models?
TextBlob = simplest, good for general text. VADER = better for social media (emojis, slang). Transformers (Hugging Face) = best accuracy, needs more compute. Start with VADER; upgrade to transformers for production.
Can I analyze non-English text?
TextBlob supports some languages (Spanish, French) via TextBlob(text, analyzer=PatternAnalyzer()). VADER is English-only. For other languages, use multilingual models from Hugging Face.
How accurate is sentiment analysis?
Lexicon methods (TextBlob, VADER): 70-80% on general text, lower on sarcasm/irony. Transformer models: 85-95%. No method is perfect — sarcasm and context remain hard. Always validate on your domain.