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