__init__.py 1.56 KB
Newer Older
1
2
3
4
5
import requests
import json

import sys

6
7
from senpy.plugins import SentimentPlugin
from senpy.models import Response, Opinion, Entry
8
9

class Sentiment140Plugin(SentimentPlugin):
10
    EXTRA_PARAMS = {
11
12
13
14
15
        "language": {"aliases": ["language", "l"],
                     "required": False,
                     "options": ["es", "en", "auto"],
                     }
    }
16
    def __init__(self, **kwargs):
17
18
19
        super(Sentiment140Plugin, self).__init__(name="sentiment140",
                                                 version="2.0",
                                                 extraparams=self.EXTRA_PARAMS,
20
21
22
                                                 **kwargs)

    def analyse(self, **params):
23
        lang = params.get("language", "auto")
24
25
        res = requests.post("http://www.sentiment140.com/api/bulkClassifyJson",
                            json.dumps({
26
                                "language": lang,
27
28
29
30
                                "data": [{"text": params["input"]}]}
                                    ))


31
        response = Response()
32
33
34
35
36
37
38
39
        polarityValue = int(res.json()["data"][0]["polarity"]) * 25
        polarity = "marl:Neutral"
        if polarityValue > 50:
            polarity = "marl:Positive"
        elif polarityValue < 50:
            polarity = "marl:Negative"


40
41
42
43
44
        entry = Entry(text=params["input"])
        opinion = Opinion(polarity=polarity, polarityValue=polarityValue)
        entry.opinions.append(opinion)
        entry.language = lang
        response.entries.append(entry)
45
46
47
        return response

plugin = Sentiment140Plugin()