Sentiment Analysis Exercise with Python Pattern Module

It connects to Twitter, searches certain content with certain hashtag and measures the sentiment around it.


In [1]:
from pattern.en import sentiment
from pattern.web import Twitter

In [2]:
twitter = Twitter()

Search for a specific hashtag.


In [3]:
keywords = "#donaldtrump OR #trump"

Set the sample size.


In [4]:
samplesize = 100

In [5]:
results = [tweet.text.lower() for tweet in twitter.search(keywords, count=samplesize)]

Compute te sentiments.


In [6]:
sentiments = [sentiment(text) for text in results]

Filter the ones with a sentiment score.


In [7]:
positivity = [res[0] for res in sentiments if res[0] > 0]
negativity = [res[0] for res in sentiments if res[0] < 0]

Compute the average sentiment.


In [8]:
total_pos_score = sum(positivity)
total_neg_score = sum(negativity)
n_pos_score = len(positivity)
n_neg_score = len(negativity)

pos_avg = 0
if (n_pos_score > 0): pos_avg = total_pos_score/n_pos_score
    
neg_avg = 0
if (n_neg_score > 0): neg_avg = total_neg_score/n_neg_score

In [9]:
print n_pos_score, pos_avg


14 0.290692640693

In [10]:
print n_neg_score, neg_avg


16 -0.41624937996

In [ ]: