bpeterso2000
3/9/2016 - 6:48 PM

Processes text through sentiment analysis and returns a dictionary containing a sentiment indicator "pos", "neg", "neutral" and the scores f

Processes text through sentiment analysis and returns a dictionary containing a sentiment indicator "pos", "neg", "neutral" and the scores for each.

"""
sentiment
~~~~~~~~~

This module processes text through the sentiment analysis API

:author: Sean Pianka <sean.pianka@gmail.com>

.. seealso:: http://text-processing.com/docs/sentiment.html

"""
import requests

SENTIMENT_API_URL = 'http://text-processing.com/api/sentiment/'


def analyze_text(text, url=SENTIMENT_API_URL):
    """Sentiment analysis

    :returns:
        {
            "label": "pos", "neg" or "neutral",
            "probability": {
                "neg": float,
                "neutral": float,
                "pos": float
            }
        }

    :raises:
        - requests.exceptions.RequestException
        - requests.exceptions.HTTPError
        - json.JSONDecodeError

    """
    response = requests.post(SENTIMENT_API_URL, data={'text': text})
    response.raise_for_status()
    return response.json()


def get_value(sentiment_api_response):
    s = sentiment_api_response['probability']
    return 0. if s['neutral'] > 0.5 else s['pos'] - s['neg']