Python nltk.sentiment.vader.SentimentIntensityAnalyzer() Examples

The following are 15 code examples of nltk.sentiment.vader.SentimentIntensityAnalyzer(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module nltk.sentiment.vader , or try the search function .
Example #1
Source File: actions.py    From rasa_workshop with MIT License 6 votes vote down vote up
def submit(self, dispatcher, tracker, domain):
        # type: (CollectingDispatcher, Tracker, Dict[Text, Any]) -> List[Dict]
        """Define what the form has to do
           after all required slots are filled
           basically it generate sentiment analysis
           using the user's feedback"""

        sid = SentimentIntensityAnalyzer()

        all_slots = tracker.slots
        for slot, value in all_slots.copy().items():
            if slot in self.required_slots(tracker):
                res = sid.polarity_scores(value)
                score = res.pop('compound', None)
                classi, confidence = max(res.items(), key=lambda x: x[1])
                # classification of the feedback, could be pos, neg, or neu
                all_slots[slot+'_class'] = classi
                # sentiment score of the feedback, range form -1 to 1
                all_slots[slot+'_score'] = score

        return [SlotSet(slot, value) for slot, value in all_slots.items()] 
Example #2
Source File: SentimentAnalysis.py    From TabPy with MIT License 5 votes vote down vote up
def SentimentAnalysis(_arg1, library="nltk"):
    """
    Sentiment Analysis is a procedure that assigns a score from -1 to 1
    for a piece of text with -1 being negative and 1 being positive. For
    more information on the function and how to use it please refer to
    tabpy-tools.md
    """
    if not (isinstance(_arg1[0], str)):
        raise TypeError

    supportedLibraries = {"nltk", "textblob"}

    library = library.lower()
    if library not in supportedLibraries:
        raise ValueError

    scores = []
    if library == "nltk":
        sid = SentimentIntensityAnalyzer()
        for text in _arg1:
            sentimentResults = sid.polarity_scores(text)
            score = sentimentResults["compound"]
            scores.append(score)
    elif library == "textblob":
        for text in _arg1:
            currScore = TextBlob(text)
            scores.append(currScore.sentiment.polarity)
    return scores 
Example #3
Source File: AdvSentiment.py    From Natural-Language-Processing-with-Python-Cookbook with MIT License 5 votes vote down vote up
def advancedSentimentAnalyzer():
    sentences = [
        ':)',
        ':(',
        'She is so :(',
        'I love the way cricket is played by the champions',
        'She neither likes coffee nor tea',
    ]
    senti = SentimentIntensityAnalyzer()
    print(' -- built-in intensity analyser --')
    for sentence in sentences:
        print('[{}]'.format(sentence), end=' --> ')
        kvp = senti.polarity_scores(sentence)
        for k in kvp:
            print('{} = {}, '.format(k, kvp[k]), end='')
        print() 
Example #4
Source File: getSentiment.py    From Stock-Analysis with MIT License 5 votes vote down vote up
def sentimentScore(sentences):
	analyzer = SentimentIntensityAnalyzer()
	results = []
	for sentence in sentences:
		vs = analyzer.polarity_scores(sentence)
		print("vs: " + str(vs))
		results.append(vs)
	return results

# sentimentScore(examples) 
Example #5
Source File: streaming.py    From Stocktalk with MIT License 5 votes vote down vote up
def on_status(self, status):
        original_tweet = status.text 

        # For every incoming tweet...
        for query in self.queries:
            if query.lower() in original_tweet.lower():
                
                # Categorize tweet
                lookup = self.reverse[query]
    
                # Increment count
                self.tracker[lookup]['volume'] += 1

                # Sentiment analysis
                if self.sentiment:
                    processed_tweet = process(original_tweet.lower())
                    score = SentimentIntensityAnalyzer().polarity_scores(processed_tweet)['compound']
                    self.tracker[lookup]['scores'].append(score)

                # Check refresh
                if elapsed_time(self.timer) >= self.refresh:
                    if not self.processing:
                        self.processing = True
                        processing_thread = threading.Thread(target=self.process)
                        processing_thread.start()
        return True 
Example #6
Source File: streaming.py    From Stocktalk with MIT License 5 votes vote down vote up
def streamer(credentials, queries, refresh, sentiment=False, debug=False):
    keywords = [i for j in queries.values() for i in j]

    # User Error Checks
    if len(queries)  <= 0:  print("Error: You must include at least one query."); return
    if len(queries)  >= 10: print("Warning: Fewer than ten query recommended.")
    if len(keywords) <= 0:  print("Error: You must include at least one keyword."); return
    if len(keywords) >= 20: print("Warning: Fewer than twenty keywords recommended.")
    if refresh       <= 0:  print("Error: Refresh rate must be greater than 0"); return

    auth = tweepy.OAuthHandler(credentials[0], credentials[1])
    auth.set_access_token(credentials[2], credentials[3])

    if sentiment:
        global SentimentIntensityAnalyzer
        from nltk.sentiment.vader import SentimentIntensityAnalyzer

    while True:

        # Start streaming -----------------------------
        try:
            print("Streaming Now...")
            listener = Listener(auth, queries, refresh, sentiment, debug)
            stream = tweepy.Stream(auth, listener)
            stream.filter(track=keywords)

        except (Timeout, ConnectionError, ReadTimeoutError):
            print("{0} Error: Connection Dropped\n".format(time.strftime('%m/%d/%Y %H:%M:%S')))
            print("Re-establishing Connection...")

        time.sleep((15*60)+1) # Wait at least 15 minutes before restarting listener

        # --------------------------------------------- 
Example #7
Source File: sent_analysis.py    From kryptoflow with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):

        self._sent_analyzer = SIA()
        self._word_tokenizer = WordPunctTokenizer().tokenize
        self._sent_tokenizer = nltk.data.LazyLoader(
            'tokenizers/punkt/english.pickle'
        ).tokenize
        self._ids = [] 
Example #8
Source File: transformation_functions.py    From sparklingml with Apache License 2.0 5 votes vote down vote up
def func(cls, *args):
        def inner(input_series):
            from nltk.sentiment.vader import SentimentIntensityAnalyzer
            # Hack until https://github.com/nteract/coffee_boat/issues/47
            try:
                sid = SentimentIntensityAnalyzer()
            except LookupError:
                import nltk
                nltk.download('vader_lexicon')
                sid = SentimentIntensityAnalyzer()
            result = input_series.apply(
                lambda sentence: sid.polarity_scores(sentence)['pos'])
            return result
        return inner 
Example #9
Source File: text.py    From pliers with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        self.analyzer = SentimentIntensityAnalyzer()
        super().__init__() 
Example #10
Source File: comparisons.py    From Fox-V3 with GNU Affero General Public License v3.0 5 votes vote down vote up
def compare(self, statement, other_statement):
        """
        Return the similarity of two statements based on
        their calculated sentiment values.

        :return: The percent of similarity between the sentiment value.
        :rtype: float
        """
        from nltk.sentiment.vader import SentimentIntensityAnalyzer

        sentiment_analyzer = SentimentIntensityAnalyzer()
        statement_polarity = sentiment_analyzer.polarity_scores(statement.text.lower())
        statement2_polarity = sentiment_analyzer.polarity_scores(other_statement.text.lower())

        statement_greatest_polarity = 'neu'
        statement_greatest_score = -1
        for polarity in sorted(statement_polarity):
            if statement_polarity[polarity] > statement_greatest_score:
                statement_greatest_polarity = polarity
                statement_greatest_score = statement_polarity[polarity]

        statement2_greatest_polarity = 'neu'
        statement2_greatest_score = -1
        for polarity in sorted(statement2_polarity):
            if statement2_polarity[polarity] > statement2_greatest_score:
                statement2_greatest_polarity = polarity
                statement2_greatest_score = statement2_polarity[polarity]

        # Check if the polarity if of a different type
        if statement_greatest_polarity != statement2_greatest_polarity:
            return 0

        values = [statement_greatest_score, statement2_greatest_score]
        difference = max(values) - min(values)

        return 1.0 - difference 
Example #11
Source File: sentiment_analysis_unsupervised_lexical.py    From text-analytics-with-python with Apache License 2.0 5 votes vote down vote up
def analyze_sentiment_vader_lexicon(review, 
                                    threshold=0.1,
                                    verbose=False):
    # pre-process text
    review = normalize_accented_characters(review)
    review = html_parser.unescape(review)
    review = strip_html(review)
    # analyze the sentiment for review
    analyzer = SentimentIntensityAnalyzer()
    scores = analyzer.polarity_scores(review)
    # get aggregate scores and final sentiment
    agg_score = scores['compound']
    final_sentiment = 'positive' if agg_score >= threshold\
                                   else 'negative'
    if verbose:
        # display detailed sentiment statistics
        positive = str(round(scores['pos'], 2)*100)+'%'
        final = round(agg_score, 2)
        negative = str(round(scores['neg'], 2)*100)+'%'
        neutral = str(round(scores['neu'], 2)*100)+'%'
        sentiment_frame = pd.DataFrame([[final_sentiment, final, positive,
                                        negative, neutral]],
                                        columns=pd.MultiIndex(levels=[['SENTIMENT STATS:'], 
                                                                      ['Predicted Sentiment', 'Polarity Score',
                                                                       'Positive', 'Negative',
                                                                       'Neutral']], 
                                                              labels=[[0,0,0,0,0],[0,1,2,3,4]]))
        print sentiment_frame
    
    return final_sentiment 
Example #12
Source File: tweetlistener.py    From tweetfeels with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sentiment(self):
        if self._sentiment is None:
            t = clean(self._data['text'])
            self._sentiment = SentimentIntensityAnalyzer().polarity_scores(t)
        return self._sentiment 
Example #13
Source File: classifiers.py    From fine-grained-sentiment with MIT License 5 votes vote down vote up
def __init__(self, model_file: str=None) -> None:
        super().__init__()
        # pip install nltk
        # python > import nltk > nltk.download() > d > vader_lexicon
        from nltk.sentiment.vader import SentimentIntensityAnalyzer
        self.vader = SentimentIntensityAnalyzer() 
Example #14
Source File: explainer.py    From fine-grained-sentiment with MIT License 5 votes vote down vote up
def __init__(self, model_file: str = None) -> None:
        from nltk.sentiment.vader import SentimentIntensityAnalyzer
        self.vader = SentimentIntensityAnalyzer()
        self.classes = np.array([1, 2, 3, 4, 5]) 
Example #15
Source File: Fetch_Data_Media_Twitter.py    From StockRecommendSystem with MIT License 4 votes vote down vote up
def getSentiments(df):
    sid = SentimentIntensityAnalyzer()
    tweet_str = ""
    for tweet in df['Text']:
        tweet_str = tweet_str + " " + tweet
    print(sid.polarity_scores(tweet_str))
    # positiveWords = ["good", "buy", "great", "bull", "up", "beast", ]
    # negativeWords = ["bad", "sell", "terrible", "bear", "down"]
    # positive = 0
    # negative = 0

    # i=1
    # for tweet in totalTweets:
    #     for word in positiveWords:
    #         if word in tweet.text.encode('utf-8'):
    #             positive += 1
    #             print(i, tweet.text.encode('utf-8'))
    #             print(tweet.created_at)
    #     for word in negativeWords:
    #         if word in tweet.text.encode('utf-8'):
    #             negative += 1
    #             print(i, tweet.text.encode('utf-8'))
    #             print(tweet.created_at)
    #     i+=1

    # print("POSITIVE TWEETS: " + str(positive))
    # print("NEGATIVE TWEETS: " + str(negative))