Tea has always been a hot topic on this blog. But tea can’t just be accepted – it must be criticized and reviewed.
Having learnt the art of Mumbai tea-making, you have collected the feedback of two customers (mother and friend) on your concoctions. But how on earth do you decipher the sentiment behind their words? Believe it or not, the answer might be a Python package called “TextBlob”.
pip install -U textblob #Installation command
What we’re going to do is create objects of type TextBlob, which we’ll initialize to contain one review each (in the form of a string). TextBlob objects have a brilliant property called “sentiment”, which evaluates how positive/how negative the response is, as well as how subjective the interpretation of the review can be. This property returns a tuple (an immutable collection) in the following format:
Over here, the polarity lies between the values : [-1.0, +1.0], where
polarity = -1 = Very negative, and
polarity = +1 = Very Positive,
subjectivity lies between the values : [0.0 to 1.0], where
subjectivity = 0.0 = Very Objective
subjectivity = +1.0 = Very Subjective
Let’s look at how to practically use TextBlob to interpret reviews.
Start the program with the line:
from textblob import TextBlob
Initialize a TextBlob object with text in the following format:
To access the sentiment behind the review, simply request for:
Here’s an example of our 3-step plan in action with the tea reviews (from mother and friend respectively).
As you can see, your mother was very critical of the tea (polarity = -1.0). However, you can take some comfort in the fact that her review was also supposed to be highly subjective (probably a result of the question statement – which was supposed to be rhetorical).
By contrast, your loyal friend has given you a strongly positive review, which is almost completely objective.
Here’s an example of some reviews with milder polarity.
You might be wondering about whether sentiments being expressed in this tuple format have any practical use. Actually, there is. Because you can access the polarity and subjectivity of a review as float variables, you can also perform whatever kind of quantitative or statistical analysis you want on them. The hard work of converting words to numbers is done. Now all you need to do is the math.
Here’s a simple example of how you could count the number of positive and negative reviews in a list.
It’s up to you to expand on the possibilities. Sentiment Analysis is used to analyse Twitter feeds, IMDB movie reviews, Amazon reviews – the list is endless. Used in conjunction with statistical algorithms and other APIs, it’s a game-changing tool in today’s data analytics industry.