Generating sentiment analysis code
The user is looking for Python code to analyze sentiment in social media posts using NLP techniques. They didn't specify a library, but I can use popular ones like NLTK, TextBlob, or HuggingFace. I’ll aim to create a functional script that might scrape or load posts and perform sentiment analysis without being overly complex. Using a pretrained model like Twitter-roberta-base-sentiment could be effective, along with sample tweets or reading from a file. I'll focus on producing self-contained, commented code.Outlining sentiment analysis steps
I want to keep the code concise while ensuring the explanation is brief. My approach includes installing necessary packages like transformers, torch, and pandas. I’ll load data from a CSV file with a 'text' column or a list. Preprocessing will clean the text by removing URLs, mentions, hashtags, and emojis without overcomplicating things. Using the HuggingFace pipeline for sentiment analysis with the CardiffNLP model is essential, as it handles labels automatically. I should also show aggregation and a basic visualization using matplotlib. I'll check label names and ensure the code runs smoothly.Streamlining sentiment analysis code
I want to simplify the process by using the pipeline for sentiment analysis with the default model 'distilbert-base-uncased-finetuned-sst-2-english'. While this one works for general English, it doesn't specifically target Twitter, and since the user mentioned "social media posts," I should use a Twitter-focused model, which is 'cardiffnlp/twitter-roberta-base-sentiment-latest'. I'll include comments to clarify.
I’ll create a structured script with a clean_text function, an analyze_sentiment function that returns results as a pandas DataFrame, and a main section generating sample posts to get printed results. I’ll skip fetching posts via the Twitter API for now.Planning the sentiment analysis script
I’m outlining a script for sentiment analysis on social media posts using a Transformer model. It will start with installation instructions in comments. The script will include functions for cleaning posts, loading them from a CSV, and creating a sentiment analysis pipeline with the CardiffNLP model.
Batch processing will be utilized for efficiency, and I’ll add a function to compute overall sentiment positivity. I’ll keep the narrative minimal and focus on providing clear code along with relevant pre-processing options, ensuring the user gets a functional script for NLP techniques.Finalizing script details
I need to ensure the code runs offline after downloading the necessary models, so I won't request internet access. It's important to be clear that users need to install the Hugging Face transformers and torch libraries, so I'll provide the appropriate pip commands. I want to keep my response concise, but I’ll make sure the code is well-annotated for clarity. Now, I’m ready to write the final version of the script! ```python
"""
Sentiment analysis for social media posts using a Transformer NLP model.
Requirements (install once):
pip install transformers torch pandas tqdm
This example:
- cleans raw social media text (mentions, URLs, hashtags, etc.)
- runs sentiment analysis with a pre-trained model
- aggregates results
You can adapt load_posts() to read from your own data source (CSV, API, DB).
"""
from future import annotations
import re
from typing import List, Iterable
import pandas as pd
from tqdm.auto import tqdm
from transformers import pipeline
----------------------------
Text cleaning utilities
----------------------------
URL_RE = re.compile(r"http\S+|www.\S+")
MENTION_RE = re.compile(r"@\w+")
HASHTAG_RE = re.compile(r"#(\w+)")
MULTISPACE_RE = re.compile(r"\s+")
def clean_post(text: str) -> str:
"""
Basic cleaning for social media text:
- Remove URLs, mentions
- Strip hashtags (#hashtag -> 'hashtag')
- Normalize whitespace
"""
text = text.lower()
text = URL_RE.sub(" ", text)
text = MENTION_RE.sub(" ", text)
text = HASHTAG_RE.sub(r"\1", text) # keep the word, drop '#'
text = MULTISPACE_RE.sub(" ", text)
return text.strip()
def clean_posts(texts: Iterable[str]) -> List[str]:
return [clean_post(t) for t in texts]
----------------------------
Sentiment pipeline
----------------------------
def build_sentiment_pipeline(
model_name: str = "cardiffnlp/twitter-roberta-base-sentiment-latest",
):
"""
Build a HuggingFace sentiment-analysis pipeline.
For generic English (not social-media-specific), you could use:
model_name="distilbert-base-uncased-finetuned-sst-2-english"
"""
clf = pipeline(
"sentiment-analysis",
model=model_name,
tokenizer=model_name,
truncation=True,
max_length=128,
)
return clf
def analyze_sentiment(
texts: List[str],
clf=None,
batch_size: int = 32,
) -> pd.DataFrame:
"""
Run sentiment analysis on a list of texts.
Returns a DataFrame:
text, clean_text, label, score
"""
if clf is None:
clf = build_sentiment_pipeline()
clean = clean_posts(texts)
all_results = []
for i in tqdm(range(0, len(clean), batch_size), desc="Analyzing sentiment"):
batch = clean[i : i + batch_size]
results = clf(batch)
all_results.extend(results)
df = pd.DataFrame(
{
"text": texts,
"clean_text": clean,
"label": [r["label"] for r in all_results],
"score": [r["score"] for r in all_results],
}
)
return df
def aggregate_sentiment(df: pd.DataFrame) -> pd.DataFrame:
"""
Compute overall sentiment distribution and mean confidence.
"""
counts = df["label"].value_counts().rename("count")
proportions = df["label"].value_counts(normalize=True).rename("proportion")
mean_score = df.groupby("label")["score"].mean().rename("mean_score")
summary = pd.concat([counts, proportions, mean_score], axis=1)
summary = summary.sort_values("proportion", ascending=False)
return summary
----------------------------
Example data loading
----------------------------
def load_posts_from_csv(
path: str,
text_column: str = "text",
n: int | None = None,
) -> List[str]:
"""
Example loader: expects a CSV with a column containing post text.
"""
df = pd.read_csv(path)
texts = df[text_column].astype(str).tolist()
if n is not None:
texts = texts[:n]
return texts
def load_example_posts() -> List[str]:
"""
Simple in-memory demo posts.
Replace this with your real data source.
"""
return [
"I love this new phone! Battery lasts forever 🔋🔥",
"Ugh, my internet is down again... so annoying.",
"The movie was okay, not great but not terrible either.",
"What an amazing game last night!! #unbelievable",
"I'm really worried about the news today.",
"Totally neutral about this feature, doesn't affect me.",
]
----------------------------
Main script
----------------------------
if name == "main":
# 1. Load posts
# Option A: from CSV
# posts = load_posts_from_csv("social_media_posts.csv", text_column="post_text", n=1000)
# Option B: from in-memory demo data
posts = load_example_posts()
# 2. Analyze sentiment
clf = build_sentiment_pipeline()
df_results = analyze_sentiment(posts, clf=clf, batch_size=8)
# 3. Aggregate / inspect
summary = aggregate_sentiment(df_results)
# 4. Show results
print("\nPer-post sentiment:")
print(df_results)
print("\nAggregated sentiment summary:")
print(summary)