当前位置: 首页>>代码示例>>Python>>正文


Python vader.SentimentIntensityAnalyzer方法代码示例

本文整理汇总了Python中nltk.sentiment.vader.SentimentIntensityAnalyzer方法的典型用法代码示例。如果您正苦于以下问题:Python vader.SentimentIntensityAnalyzer方法的具体用法?Python vader.SentimentIntensityAnalyzer怎么用?Python vader.SentimentIntensityAnalyzer使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在nltk.sentiment.vader的用法示例。


在下文中一共展示了vader.SentimentIntensityAnalyzer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: advancedSentimentAnalyzer

# 需要导入模块: from nltk.sentiment import vader [as 别名]
# 或者: from nltk.sentiment.vader import SentimentIntensityAnalyzer [as 别名]
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() 
开发者ID:PacktPublishing,项目名称:Natural-Language-Processing-with-Python-Cookbook,代码行数:18,代码来源:AdvSentiment.py

示例2: submit

# 需要导入模块: from nltk.sentiment import vader [as 别名]
# 或者: from nltk.sentiment.vader import SentimentIntensityAnalyzer [as 别名]
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()] 
开发者ID:Cheukting,项目名称:rasa_workshop,代码行数:23,代码来源:actions.py

示例3: SentimentAnalysis

# 需要导入模块: from nltk.sentiment import vader [as 别名]
# 或者: from nltk.sentiment.vader import SentimentIntensityAnalyzer [as 别名]
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 
开发者ID:tableau,项目名称:TabPy,代码行数:30,代码来源:SentimentAnalysis.py

示例4: getSentiments

# 需要导入模块: from nltk.sentiment import vader [as 别名]
# 或者: from nltk.sentiment.vader import SentimentIntensityAnalyzer [as 别名]
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)) 
开发者ID:doncat99,项目名称:StockRecommendSystem,代码行数:29,代码来源:Fetch_Data_Media_Twitter.py

示例5: sentimentScore

# 需要导入模块: from nltk.sentiment import vader [as 别名]
# 或者: from nltk.sentiment.vader import SentimentIntensityAnalyzer [as 别名]
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) 
开发者ID:Vaibhav,项目名称:Stock-Analysis,代码行数:12,代码来源:getSentiment.py

示例6: on_status

# 需要导入模块: from nltk.sentiment import vader [as 别名]
# 或者: from nltk.sentiment.vader import SentimentIntensityAnalyzer [as 别名]
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 
开发者ID:anfederico,项目名称:Stocktalk,代码行数:28,代码来源:streaming.py

示例7: streamer

# 需要导入模块: from nltk.sentiment import vader [as 别名]
# 或者: from nltk.sentiment.vader import SentimentIntensityAnalyzer [as 别名]
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

        # --------------------------------------------- 
开发者ID:anfederico,项目名称:Stocktalk,代码行数:35,代码来源:streaming.py

示例8: __init__

# 需要导入模块: from nltk.sentiment import vader [as 别名]
# 或者: from nltk.sentiment.vader import SentimentIntensityAnalyzer [as 别名]
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 = [] 
开发者ID:carlomazzaferro,项目名称:kryptoflow,代码行数:10,代码来源:sent_analysis.py

示例9: func

# 需要导入模块: from nltk.sentiment import vader [as 别名]
# 或者: from nltk.sentiment.vader import SentimentIntensityAnalyzer [as 别名]
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 
开发者ID:sparklingpandas,项目名称:sparklingml,代码行数:16,代码来源:transformation_functions.py

示例10: __init__

# 需要导入模块: from nltk.sentiment import vader [as 别名]
# 或者: from nltk.sentiment.vader import SentimentIntensityAnalyzer [as 别名]
def __init__(self):
        self.analyzer = SentimentIntensityAnalyzer()
        super().__init__() 
开发者ID:tyarkoni,项目名称:pliers,代码行数:5,代码来源:text.py

示例11: compare

# 需要导入模块: from nltk.sentiment import vader [as 别名]
# 或者: from nltk.sentiment.vader import SentimentIntensityAnalyzer [as 别名]
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 
开发者ID:bobloy,项目名称:Fox-V3,代码行数:38,代码来源:comparisons.py

示例12: analyze_sentiment_vader_lexicon

# 需要导入模块: from nltk.sentiment import vader [as 别名]
# 或者: from nltk.sentiment.vader import SentimentIntensityAnalyzer [as 别名]
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 
开发者ID:dipanjanS,项目名称:text-analytics-with-python,代码行数:32,代码来源:sentiment_analysis_unsupervised_lexical.py

示例13: sentiment

# 需要导入模块: from nltk.sentiment import vader [as 别名]
# 或者: from nltk.sentiment.vader import SentimentIntensityAnalyzer [as 别名]
def sentiment(self):
        if self._sentiment is None:
            t = clean(self._data['text'])
            self._sentiment = SentimentIntensityAnalyzer().polarity_scores(t)
        return self._sentiment 
开发者ID:uclatommy,项目名称:tweetfeels,代码行数:7,代码来源:tweetlistener.py

示例14: __init__

# 需要导入模块: from nltk.sentiment import vader [as 别名]
# 或者: from nltk.sentiment.vader import SentimentIntensityAnalyzer [as 别名]
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() 
开发者ID:prrao87,项目名称:fine-grained-sentiment,代码行数:8,代码来源:classifiers.py

示例15: __init__

# 需要导入模块: from nltk.sentiment import vader [as 别名]
# 或者: from nltk.sentiment.vader import SentimentIntensityAnalyzer [as 别名]
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]) 
开发者ID:prrao87,项目名称:fine-grained-sentiment,代码行数:6,代码来源:explainer.py


注:本文中的nltk.sentiment.vader.SentimentIntensityAnalyzer方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。