Himanshu Lohiya
1 min readJul 4, 2018

Sentiment Analysis with TextBlob

TextBlob is excellent open-source library for performing NLP tasks.

It’s a sentiment lexicon (in the form of an XML file) which it leverages to give both polarity and subjectivity scores.

The polarity score is a float within the range [-1.0, 1.0].

The subjectivity is a float within the range [0.0, 1.0]
0.0 is very objective and
1.0 is very subjective.

The scores from TextBlob are normalised scale as compare to Afinn.

Let’s get the sentiment polarity and labels for each news article and aggregate the summary statistics per news category.

For a data frame if you want new column with sentimenet analysis for the text that you have in a column(TEXT) on different rows then

def sentiment(text):
try:
return TextBlob(text).sentiment
except:
return None

To add a new column in your data frame with sentiment analysis :

df['Polarity]     = df[TEXT].apply(sentiment).apply(lambda x: x[0])
df['Subjectivity] = df[TEXT].apply(sentiment).apply(lambda x: x[1])

Lets apply the technique to one of the data frame we got from the scraping :

Let’s look at the sentiment frequency distribution per category.

Responses (1)