sentiment140.py 1.41 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"
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
23
        if polarity_value > 50:
24
            polarity = "marl:Positive"
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
25
        elif polarity_value < 50:
26
            polarity = "marl:Negative"
27
28
29
        entry = Entry(id="Entry0",
                      text=params["input"],
                      prefix=p)
30
        opinion = Opinion(id="Opinion0",
31
                          prefix=p,
32
33
                          hasPolarity=polarity,
                          polarityValue=polarity_value)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
34
        opinion["prov:wasGeneratedBy"] = self.id
35
36
37
        entry.opinions.append(opinion)
        entry.language = lang
        response.entries.append(entry)
38
        return response