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

4
from senpy.plugins import SentimentPlugin
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
5
from senpy.models import Results, Sentiment, 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
YAPFed    
J. Fernando Sánchez committed
12
13
14
15
16
17
                            json.dumps({
                                "language": lang,
                                "data": [{
                                    "text": params["input"]
                                }]
                            }))
18

19
        p = params.get("prefix", None)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
20
        response = Results(prefix=p)
J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
21
22
        polarity_value = self.maxPolarityValue * int(res.json()["data"][0][
            "polarity"]) * 0.25
23
        polarity = "marl:Neutral"
24
25
        neutral_value = self.maxPolarityValue / 2.0
        if polarity_value > neutral_value:
26
            polarity = "marl:Positive"
27
        elif polarity_value < neutral_value:
28
            polarity = "marl:Negative"
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
29

J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
30
31
32
33
34
35
        entry = Entry(id="Entry0", nif__isString=params["input"])
        sentiment = Sentiment(
            id="Sentiment0",
            prefix=p,
            marl__hasPolarity=polarity,
            marl__polarityValue=polarity_value)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
36
37
38
        sentiment.prov__wasGeneratedBy = self.id
        entry.sentiments = []
        entry.sentiments.append(sentiment)
39
40
        entry.language = lang
        response.entries.append(entry)
41
        return response