Twitter Sentiment Analysis in Python

Patrick Gichini
MindNinja
Published in
2 min readApr 17, 2019

We looked at Twitter sentiments using R in my previous post. You can check it out if you’re interested.

I thought it might be cool if I also did one for Python since not everyone is an R fun and what the hell? Am bored.

Just like in R, there are two ways of doing sentiment analysis:

1 Lexicons and

2 Machine Learning Techniques.

For this article, we’ll go the lexicon way. I will be using TextBlob

I am not a Python guy so I found out about TextBlob last week but I have to say it’s pretty cool. It is a textual data processing library that allows you to do common NLP tasks. You can read my short intro to TextBlob here.

Note that if you don’t have TextBlob, you’ll have to install it using pip. For our activity, you’ also need tweepy. Tweepy is an easy to use python library for accessing Twitter data.

After everything is all set, create a new python file: twitter_sentiments.py

The first thing we’ll do is import all the needed libraries

import tweepy
from textblob import TextBlob

Then, we’ll have to define our connection tokens

consumer_key = 'xxxxxxxxxxxxxx'
consumer_secret = 'xxxxxxxxxxxxxxxxxx'
access_token = 'xxxxxxxxxxxxxxxx'
access_secret = 'xxxxxxxxxxxxxxxxx'

If this is your first time doing any Twitter stuff, refer to R analysis post to see how to create an app and generate tokens.

After that is done, we’ll need to generate an oauth file to connect to Twitter

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)

After that has been done, we’ll need to specify our query

tweets = api.search('Climate')

Now that we have the tweets, it’s time to do the magic. Among the many NLP tasks that TextBlob can do, sentiment analysis is there. TextBlob’s sentiments are divided into two: polarity and subjectivity.

Polarity has a range between [-1.0, 1.0] which is usually a float. A value of -1.0 is negative while that of 1.0 is positive.

Subjectivity has a range between [0.0, 1.0] which is a float. A value of 0.0 is very objective while 1.0 is very subjective. Objective means that the text is mostly factual while subjective means that the text is more opinionated and emotional.

We are going to divide our tweets into positive, negative or neutral sections.

This will list all the Tweets, their polarity and subjectivity values and tell us their sentiment status as we’ve defined them above.

Enjoyed the read? Find more cool tech tricks on MindNinja.

--

--

Patrick Gichini
MindNinja

Linux Ninja | Data Enthusiast | Sentimental Poet | Agent Boyfriend