Skip to content

Instantly share code, notes, and snippets.

@jamesgeorge007
Created April 15, 2018 10:27
Show Gist options
  • Save jamesgeorge007/54c7e6c5a8373e2da5305a0734b65def to your computer and use it in GitHub Desktop.
Save jamesgeorge007/54c7e6c5a8373e2da5305a0734b65def to your computer and use it in GitHub Desktop.
Comparison across two twitter handles using the IBM watson Personality Insights API. It requires API keys to be generated with your IBM Bluemix account.
import sys
import operator
import requests
import json
import twitter
from watson_developer_cloud import PersonalityInsightsV2 as PersonalityInsights
def analyze(handle):
twitter_consumer_key='QGi7GvLXA9N5pn9xfGOoSVdSx'
twitter_consumer_secret='GjpHa6HAW2vj7uElb7CvRH5PTjsZOKF7dnaCRstEtOuAZmNvWa'
twitter_access_token='772688937328357376-oChaOafdFmloDgp4bVMb2AfHP60eZmM'
twitter_access_secret='Clrfk8TuzoEDR8Djt9OA29Ky8U8qb4KqN4XCXRrG9P2Ao'
twitter_api=twitter.Api(consumer_key=twitter_consumer_key, consumer_secret=twitter_consumer_secret,access_token_key=twitter_access_token, access_token_secret=twitter_access_secret)
statuses = twitter_api.GetUserTimeline(screen_name=handle, count=200, include_rts=False)
text=""
for status in statuses:
if status.lang=='en':
text+=status.text.encode('utf-8')
pi_username='0e533f92-50d3-438e-8c7f-9c78452ecaf0'
pi_password='Uqm2KqeiVybN'
personality_insights=PersonalityInsights(username=pi_username,password=pi_password)
pi_result=personality_insights.profile(text)
return pi_result
def flatten(orig):
data = {}
for c in orig['tree']['children']:
if 'children' in c:
for c2 in c['children']:
if 'children' in c2:
for c3 in c2['children']:
if 'children' in c3:
for c4 in c3['children']:
if (c4['category'] == 'personality'):
data[c4['id']] = c4['percentage']
if 'children' not in c3:
if (c3['category'] == 'personality'):
data[c3['id']] = c3['percentage']
return data
def compare(dict1, dict2):
compared_data = {}
for keys in dict1:
if dict1[keys] != dict2[keys]:
compared_data[keys]=abs(dict1[keys] - dict2[keys])
return compared_data
user_handle = "@Codecademy"
celebrity_handle = "@IBM"
user_result=analyze(user_handle)
celebrity_result=analyze(celebrity_handle)
user=flatten(user_result)
celebrity=flatten(celebrity_result)
compared_results=compare(user,celebrity)
sorted_result = sorted(compared_results.items(), key=operator.itemgetter(1))
for keys, value in sorted_result[:5]:
print(keys,end='')
print(user[keys]),
print('->'),
print(celebrity[keys]),
print('->'),
print(compared_results[keys])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment