Skip to content

Instantly share code, notes, and snippets.

@zdepablo
Created March 3, 2014 15:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zdepablo/9327177 to your computer and use it in GitHub Desktop.
Save zdepablo/9327177 to your computer and use it in GitHub Desktop.
Analyze Twitter sentiment for your brand using Textalytics Media Analysis API
import smaclient
from TwitterAPI import TwitterAPI
import matplotlib.pyplot as plt
# Go to http://dev.twitter.com and create an app.
# The consumer key and secret will be generated for you after
consumer_key = <consumer-key>
consumer_secret = <consumer-secret>
# After the step above, you will be redirected to your app's page.
# Create an access token under the the "Your access token" section
access_token_key = <access-token-key>
access_token_secret = <access-token-secret>
# Register in https://textalytics.com
# Log in and get a licence for Textalytics Media Analysis API
license_key = <textalytics-license-key>
# Create a Twitter client
twitter = TwitterAPI(consumer_key, consumer_secret, access_token_key, access_token_secret)
# Create a Textalytics client
textalytics = smaclient.SmaClient(license_key)
textalytics.fields = 'sentiment'
# Analyze sentiment for Nokia in Spanish, retrieve at most 100 tweets
brand = 'Nokia'
language = 'es'
max_tweets = 100
labels = ['P', 'N', 'NEU', 'NONE']
colors = ['yellowgreen','lightcoral','gold','lightskyblue']
# Initialize sentiments to aggregate sentiment count
total = 0
sentiments = {}
for label in labels:
sentiments[label] = 0
# Search and analyze tweets
query = {'q' : brand, 'lang' : language, 'count': max_tweets}
results = twitter.request('search/tweets', query )
for tweet in results.get_iterator():
doc = smaclient.Document(tweet['id'], tweet['text'])
doc.language = language
doc.source = 'TWITTER'
response = textalytics.analyze(doc)
if (isinstance(response,smaclient.Response)):
print response.result.sentiment, ' ', tweet['text']
sentiments[response.result.sentiment] = sentiments[response.result.sentiment] + 1
total = total + 1
# Plot a pie chart
sizes = [sentiments['P']/float(total), sentiments['N']/float(total), sentiments['NEU']/float(total), sentiments['NONE']/float(total)]
print sizes
plt.pie(sizes,labels=labels, colors=colors, autopct='%1.1f%%', shadow=True)
plt.title(brand + ' sentiment using Textalytics Media Analysis 1.0')
plt.axis('equal')
plt.show()
@Shrutiarora1103
Copy link

Hi zdepablo, I am facing error running your code.The error is with smaclient which is no more supported in python packages.Can you please help?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment