← All projects

Twitter Sentiment Analysis

Searches Twitter for any keyword, cleans the tweets, and scores how positive, negative or neutral the conversation is, then surfaces the phrases people use most to predict where the conversation goes next.

  • Python
  • Pandas
  • NumPy
  • NLTK
  • scikit-learn
  • Plotly
  • Matplotlib
  • Jupyter

Twitter Sentiment Analysis answers a simple question: how does Twitter feel about this right now? You give it a keyword or phrase and a number of tweets, and it pulls them live from the Twitter API, cleans them up, scores the sentiment of each one, and charts the overall mood. It also looks at which phrases come up most often, to suggest how the conversation is likely to continue.

How it works

  1. Collect. Searches the Twitter API (via Tweepy) for the keyword and fetches the requested number of tweets. API keys are read from local files, so they never sit in the notebook.
  2. Clean. Raw tweets are noisy, so each one is stripped of retweet prefixes, @mentions, links, HTML, emoji and punctuation, contractions are expanded, and duplicates are dropped.
  3. Score. Every tweet gets a sentiment score from two lexicon-based models: NLTK's VADER (positive, negative, neutral and compound scores) and TextBlob (polarity and subjectivity). Each tweet is labelled positive, negative or neutral.
  4. Analyse the language. Tweets are tokenized, stop words removed and words stemmed to their roots, then counted to find the most common words, and the top 2-, 3- and 4-word phrases (n-grams). The most frequent phrases show what people are saying and how they tend to say it next.
  5. Visualize. Interactive Plotly pie and bar charts show the sentiment split, and a Matplotlib and seaborn dashboard plots every tweet's scores, plus word counts, tweet lengths and the top n-grams.

Why cleaning matters

On a sample run of 500 tweets, removing duplicates and retweets left 258 unique tweets, and the measured mood shifted noticeably: the negative share rose from about 16% to 22%, and neutral fell from 71% to 64%. Repeated retweets and link-heavy tweets had been diluting the real signal, which is why the cleaning step sits before any scoring.