sentiment140.py 1.52 KB
Newer Older
1
2
3
import requests
import json

4
from senpy.plugins import SentimentPlugin
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
5
from senpy.models import Results, Sentiment, Entry
6

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
7

8
9
class Sentiment140Plugin(SentimentPlugin):
    def analyse(self, **params):
10
        lang = params.get("language", "auto")
11
        res = requests.post("http://www.sentiment140.com/api/bulkClassifyJson",
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
12
13
14
15
16
                            json.dumps({"language": lang,
                                        "data": [{"text": params["input"]}]
                                        }
                                       )
                            )
17

18
        p = params.get("prefix", None)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
19
        response = Results(prefix=p)
20
21
        polarity_value = self.maxPolarityValue*int(res.json()["data"][0]
                                                   ["polarity"]) * 0.25
22
        polarity = "marl:Neutral"
23
24
        neutral_value = self.maxPolarityValue / 2.0
        if polarity_value > neutral_value:
25
            polarity = "marl:Positive"
26
        elif polarity_value < neutral_value:
27
            polarity = "marl:Negative"
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
28

29
        entry = Entry(id="Entry0",
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
30
31
32
33
34
35
36
37
                      nif__isString=params["input"])
        sentiment = Sentiment(id="Sentiment0",
                            prefix=p,
                            marl__hasPolarity=polarity,
                            marl__polarityValue=polarity_value)
        sentiment.prov__wasGeneratedBy = self.id
        entry.sentiments = []
        entry.sentiments.append(sentiment)
38
39
        entry.language = lang
        response.entries.append(entry)
40
        return response