sentiment140.py 1.64 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 Sentiment
6

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
7

8
class Sentiment140Plugin(SentimentPlugin):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
9
    def analyse_entry(self, entry, 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
                            json.dumps({
                                "language": lang,
                                "data": [{
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
15
                                    "text": entry.text
J. Fernando Sánchez's avatar
YAPFed  
J. Fernando Sánchez committed
16 17
                                }]
                            }))
18
        p = params.get("prefix", None)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
19 20
        polarity_value = self.maxPolarityValue * int(
            res.json()["data"][0]["polarity"]) * 0.25
21
        polarity = "marl:Neutral"
22 23
        neutral_value = self.maxPolarityValue / 2.0
        if polarity_value > neutral_value:
24
            polarity = "marl:Positive"
25
        elif polarity_value < neutral_value:
26
            polarity = "marl:Negative"
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
27

J. Fernando Sánchez's avatar
YAPFed  
J. Fernando Sánchez committed
28 29 30 31
        sentiment = Sentiment(
            prefix=p,
            marl__hasPolarity=polarity,
            marl__polarityValue=polarity_value)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
32 33 34
        sentiment.prov__wasGeneratedBy = self.id
        entry.sentiments = []
        entry.sentiments.append(sentiment)
35
        entry.language = lang
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
36
        yield entry
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

    test_cases = [
        {
            'entry': {
                'text': 'I love Titanic'
            },
            'params': {},
            'expected': {
                "text": "I love Titanic",
                'sentiments': [
                    {
                        'marl:hasPolarity': 'marl:Positive',
                    }
                ]
            }
        }
    ]