Created
September 3, 2012 21:47
-
-
Save joestump/3613823 to your computer and use it in GitHub Desktop.
A simple JSON only Alchemy API client for Python using the requests library.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import urllib | |
class AlchemyAPI(object): | |
BASE_URL = 'https://access.alchemyapi.com' | |
def __init__(self, api_key): | |
self.api_key = api_key | |
def keywords(self, text): | |
results = self._call_endpoint('TextGetRankedKeywords', text) | |
return [{'relevance': float(k['relevance']), 'text': k['text']} for k in | |
results['keywords']] | |
def sentiment(self, text): | |
results = self._call_endpoint('TextGetTextSentiment', text) | |
return (float(results['docSentiment']['score']), | |
results['docSentiment']['type']) | |
def _call_endpoint(self, name, text): | |
endpoint = self._endpoint(name, text=text) | |
resp = requests.get(endpoint) | |
if resp.status_code != 200: | |
raise Exception('API returned %s' % resp.status_code) | |
if resp.json['status'] != 'OK': | |
raise Exception('API status was not OK (%s)' % resp.json['status']) | |
return resp.json | |
def _endpoint(self, name, **kwargs): | |
kwargs.update({ | |
'apikey': self.api_key, | |
'outputMode': 'json', | |
}) | |
return '%s/calls/text/%s?%s' % (self.BASE_URL, name, urllib.urlencode(kwargs)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment