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

4
5
from senpy.plugins import SentimentPlugin
from senpy.models import Response, Opinion, 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
19
        p = params.get("prefix", None)
        response = Response(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"
28
29
30
        entry = Entry(id="Entry0",
                      text=params["input"],
                      prefix=p)
31
        opinion = Opinion(id="Opinion0",
32
                          prefix=p,
33
34
                          hasPolarity=polarity,
                          polarityValue=polarity_value)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
35
        opinion["prov:wasGeneratedBy"] = self.id
36
37
38
        entry.opinions.append(opinion)
        entry.language = lang
        response.entries.append(entry)
39
        return response