sentiment140.py 1.26 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()
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"
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
25
26
27
28
29
30
        entry = Entry(text=params["input"],
                      prefix=params.get("prefix", ""))
        opinion = Opinion(hasPolarity=polarity,
                          polarityValue=polarity_value,
                          prefix=params.get("prefix", ""))
        opinion["prov:wasGeneratedBy"] = self.id
31
32
33
        entry.opinions.append(opinion)
        entry.language = lang
        response.entries.append(entry)
34
        return response