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