Skip to content

Instantly share code, notes, and snippets.

@daTokenizer
Last active November 10, 2015 15:47
Show Gist options
  • Save daTokenizer/ca8ff0d1282443020f6f to your computer and use it in GitHub Desktop.
Save daTokenizer/ca8ff0d1282443020f6f to your computer and use it in GitHub Desktop.
BASE_URL = 'http://access.alchemyapi.com/calls'
SENTIMENT_URL = "/text/TextGetTargetedSentiment"
API_KEY = "add it here"
try:
from urllib.request import urlopen
from urllib.parse import urlparse
from urllib.parse import urlencode
except ImportError:
from urlparse import urlparse
from urllib2 import urlopen
from urllib import urlencode
try:
import json
except ImportError:
# Older versions of Python (i.e. 2.4) require simplejson instead of json
import simplejson as json
try:
import urlfetch
except ImportError:
from google.appengine.api import urlfetch
class SentimentAnalyzer(object):
def __init__(self):
self.default_params = {
'apikey' : API_KEY,
'outputMode' : 'json',
'linkedData':'1',
'showSourceText':'1'
}
def get_sentiment(self, text, target):
print "got text:", text
print "got target:", target
data = self.default_params
data['text'] = text
data['target'] = target
post_url = ""
service_URI = BASE_URL + SENTIMENT_URL
try:
post_url = service_URI + \
'?' + urlencode(data).encode('utf-8')
except TypeError:
post_url = service_URI + '?' + urlencode(data)
results = ""
try:
results = urlfetch.fetch(url=post_url,deadline=8)
except Exception as e:
print(e)
return {'status': 'ERROR', 'statusInfo': 'network-error'}
try:
return json.load(results)
except:
try:
return json.loads(results.content)
except Exception as e:
if results != "":
print(results)
print(e)
return {'status': 'ERROR', 'statusInfo': 'parse-error'}
@daTokenizer
Copy link
Author

you can use this just like you use the original requests-using alchemy.py api by invoking:
SentimentAnalyzer().get_sentiment(text, tsrget)

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