SentimentAnalysis()   B
last analyzed

Complexity

Conditions 7

Size

Total Lines 28
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 28
rs 8
c 0
b 0
f 0
cc 7
nop 2
1
from textblob import TextBlob
2
import nltk
3
from nltk.sentiment.vader import SentimentIntensityAnalyzer
4
from tabpy.models.utils import setup_utils
5
6
7
import ssl
8
9
_ctx = ssl._create_unverified_context
10
ssl._create_default_https_context = _ctx
11
12
13
nltk.download("vader_lexicon")
14
nltk.download("punkt")
15
16
17
def SentimentAnalysis(_arg1, library="nltk"):
18
    """
19
    Sentiment Analysis is a procedure that assigns a score from -1 to 1
20
    for a piece of text with -1 being negative and 1 being positive. For
21
    more information on the function and how to use it please refer to
22
    tabpy-tools.md
23
    """
24
    if not (isinstance(_arg1[0], str)):
25
        raise TypeError
26
27
    supportedLibraries = {"nltk", "textblob"}
28
29
    library = library.lower()
30
    if library not in supportedLibraries:
31
        raise ValueError
32
33
    scores = []
34
    if library == "nltk":
35
        sid = SentimentIntensityAnalyzer()
36
        for text in _arg1:
37
            sentimentResults = sid.polarity_scores(text)
38
            score = sentimentResults["compound"]
39
            scores.append(score)
40
    elif library == "textblob":
41
        for text in _arg1:
42
            currScore = TextBlob(text)
43
            scores.append(currScore.sentiment.polarity)
44
    return scores
45
46
47
if __name__ == "__main__":
48
    setup_utils.deploy_model(
49
        "Sentiment Analysis",
50
        SentimentAnalysis,
51
        "Returns a sentiment score between -1 and 1 for " "a given string",
52
    )
53