From 86fdd8678a0dfcf2089ccf49e5b3219e28f84cae Mon Sep 17 00:00:00 2001 From: militarpancho Date: Mon, 8 May 2017 13:20:47 +0200 Subject: [PATCH] Add aggregate sentiment. This closes senpy/senpy-plugins-community#10 --- .../sentiment-meaningCloud.py | 56 ++++++++++++++----- 1 file changed, 41 insertions(+), 15 deletions(-) diff --git a/sentiment-meaningCloud/sentiment-meaningCloud.py b/sentiment-meaningCloud/sentiment-meaningCloud.py index 1ba9cd2..3cc51ad 100644 --- a/sentiment-meaningCloud/sentiment-meaningCloud.py +++ b/sentiment-meaningCloud/sentiment-meaningCloud.py @@ -1,4 +1,5 @@ import time +import logging import requests import json import string @@ -8,7 +9,22 @@ import time from senpy.plugins import SentimentPlugin, SenpyPlugin from senpy.models import Results, Entry, Sentiment,Error +logger = logging.getLogger(__name__) + class DaedalusPlugin(SentimentPlugin): + + + def _polarity(self, value): + + polarityValue = 0 + polarity = 'marl:Neutral' + if 'N' in value: + polarity = 'marl:Negative' + polarityValue = -1 + elif 'P' in value: + polarity = 'marl:Positive' + polarityValue = 1 + return polarity, polarityValue def analyse_entry(self, entry, params): @@ -28,22 +44,32 @@ class DaedalusPlugin(SentimentPlugin): r = requests.post(api, params=parameters, timeout=3) except requests.exceptions.Timeout: raise Error("Meaning Cloud API does not response") - value = r.json().get('score_tag', None) - if not value: + api_response = r.json() + if not api_response.get('score_tag'): raise Error(r.json()) - #Senpy Response response = Results() - polarityValue = 0 - polarity = 'marl:Neutral' - if 'N' in value: - polarity = 'marl:Negative' - polarityValue = -1 - elif 'P' in value: - polarity = 'marl:Positive' - polarityValue = 1 - - opinion = Sentiment(id="Opinion0",marl__hasPolarity=polarity,marl__polarityValue = polarityValue) - entry.sentiments.append(opinion) + agg_polarity, agg_polarityValue = self._polarity(api_response.get('score_tag', None)) + agg_opinion = Sentiment(id="Opinion0", + marl__hasPolarity=agg_polarity, + marl__polarityValue = agg_polarityValue, + marl__opinionCount = len(api_response['sentence_list'])) + entry.sentiments.append(agg_opinion) + logger.info(api_response['sentence_list']) + count = 1 + for sentence in api_response['sentence_list']: + for nopinion in sentence['segment_list']: + logger.info(nopinion) + polarity, polarityValue = self._polarity(nopinion.get('score_tag', None)) + opinion = Sentiment(id="Opinion{}".format(count), + marl__hasPolarity=polarity, + marl__polarityValue=polarityValue, + marl__aggregatesOpinion=agg_opinion.get('id'), + nif__anchorOf=nopinion.get('text', None), + nif__beginIndex=nopinion.get('inip', None), + nif__endIndex=nopinion.get('endp', None) + ) - yield entry \ No newline at end of file + count += 1 + entry.sentiments.append(opinion) + yield entry