Python NLTK 情感分析不正确

在这里插入图片描述

1、问题背景

一位 Reddit 用户使用 Python 的 NLTK 库来训练一个朴素贝叶斯分类器以研究其他句子的情感,但是无论输入什么句子,分类器总是预测为正面。

2、解决方案

经过仔细检查,发现原始代码中的问题在于 wordList 为空。因此,需要将 wordList 赋值为从推文中提取的单词特征。修改后的代码如下:

wordList = getwordfeatures(getwords(tweets))
wordList = [i for i in wordList if not i in stopwords.words('english')]
wordList = [i for i in wordList if not i in customstopwords]

以下是完整的修复代码:

import nltk
import math
import re
import sys
import os
import codecs
reload(sys)
sys.setdefaultencoding('utf-8')

from nltk.corpus import stopwords

__location__ = os.path.realpath(
    os.path.join(os.getcwd(), os.path.dirname(__file__)))

postweet = __location__ + "/postweet.txt"
negtweet = __location__ + "/negtweet.txt"

customstopwords = ['band', 'they', 'them']

# Load positive tweets into a list
p = open(postweet, 'r')
postxt = p.readlines()

# Load negative tweets into a list
n = open(negtweet, 'r')
negtxt = n.readlines()

neglist = []
poslist = []

# Create a list of 'negatives' with the exact length of our negative tweet list.
for i in range(0, len(negtxt)):
    neglist.append('negative')

# Likewise for positive.
for i in range(0, len(postxt)):
    poslist.append('positive')

# Creates a list of tuples, with sentiment tagged.
postagged = zip(postxt, poslist)
negtagged = zip(negtxt, neglist)

# Combines all of the tagged tweets to one large list.
taggedtweets = postagged + negtagged

tweets = []

# Create a list of words in the tweet, within a tuple.
for (word, sentiment) in taggedtweets:
    word_filter = [i.lower() for i in word.split()]
    tweets.append((word_filter, sentiment))

# Pull out all of the words in a list of tagged tweets, formatted in tuples.
def getwords(tweets):
    allwords = []
    for (words, sentiment) in tweets:
        allwords.extend(words)
    return allwords

# Order a list of tweets by their frequency.
def getwordfeatures(listoftweets):
    # Print out wordfreq if you want to have a look at the individual counts of words.
    wordfreq = nltk.FreqDist(listoftweets)
    words = wordfreq.keys()
    return words

# Calls above functions - gives us list of the words in the tweets, ordered by freq.
print(getwordfeatures(getwords(tweets)))

wordList = getwordfeatures(getwords(tweets))
wordList = [i for i in wordList if not i in stopwords.words('english')]
wordList = [i for i in wordList if not i in customstopwords]

def feature_extractor(doc):
    docwords = set(doc)
    features = {}
    for i in wordList:
        features['contains(%s)' % i] = (i in docwords)
    return features

# Creates a training set - classifier learns distribution of true/falses in the input.
training_set = nltk.classify.apply_features(feature_extractor, tweets)
classifier = nltk.NaiveBayesClassifier.train(training_set)

print(classifier.show_most_informative_features(n=30))

while True:
    input = raw_input('ads')
    if input == 'exit':
        break
    elif input == 'informfeatures':
        print(classifier.show_most_informative_features(n=30))
        continue
    else:
        input = input.lower()
        input = input.split()
        print('\nWe think that the sentiment was ' + classifier.classify(feature_extractor(input)) + ' in that sentence.\n')

p.close()
n.close()

用户可以根据需要调整 customstopwords 列表以过滤掉不相关的词语。

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: NLTK(自然语言工具包)是一个流行的Python库,用于自然语言处理。情感分析是其中一个重要的应用领域,可以使用NLTK进行情感分析。首先,需要下载NLTK库并安装。 然后,可以使用NLTK提供的情感分析模块VADER进行情感分析。VADER使用一种基于规则的方法,可以分析出文本中的情感极性(positive、negative或neutral),以及情感强度(强、中等或弱)。 以下是一个简单的例子,使用NLTK对一些文本进行情感分析: ``` python import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer nltk.download('vader_lexicon') # 初始化情感分析器 sia = SentimentIntensityAnalyzer() # 要分析的文本 text = "This movie is really great, I enjoyed it a lot!" # 进行情感分析 sentiment = sia.polarity_scores(text) # 输出情感分析结果 print(sentiment) ``` 输出结果为: ``` {'neg': 0.0, 'neu': 0.473, 'pos': 0.527, 'compound': 0.6114} ``` 其中,`compound`是一个综合指标,可以表示文本的整体情感极性和强度。在这个例子中,分析结果为正向情感,且强度较强(`compound`值为0.6114)。 ### 回答2: Pythonnltk库(Natural Language Toolkit)提供了许多自然语言处理的功能,其中包括情感分析情感分析是一种通过分析文本来确定其中蕴含的情感或情绪的技术。 在nltk库中,有几种方式可以进行情感分析。其中一种常用的方法是使用情感词典。情感词典是一个包含单词和对应情感极性(如正面、负面、中性)的列表。通过计算文本中出现的情感词的数量和其极性,可以对整段文本的情感进行评估。 另一种方法是通过训练情感分类器来进行情感分析。这可以通过使用已标记的文本数据集进行监督学习来实现。训练过程中,计算机会学习如何将文本与特定情感类别相关联。然后,使用训练好的分类器可以对新的文本进行情感分析。 除此之外,nltk库还提供了其他处理文本的功能,如分词、词干提取、词性标注等。这些功能可以结合情感分析一起使用,以进一步提高情感分析的准确性和效果。 总的来说,Pythonnltk库提供了强大的情感分析工具,可以帮助我们分析文本中的情感和情绪。无论是通过情感词典还是训练分类器,都可以在实际应用中对情感进行有效的分析和评估。 ### 回答3: Python nltk是一个常用的自然语言处理工具库,其提供了丰富的功能以支持情感分析任务。 首先,nltk中提供了一组用于处理文本数据的方法和函数。通过nltk,我们可以对文本进行预处理,例如清除噪声、分词、标记标点和词性等等。这些预处理步骤对于情感分析非常重要,因为它可以提供干净、规范化的文本数据作为输入。 其次,nltk还包括了一些常用的情感分析算法和库。其中最常用的是情感词典,它包含了一系列单词和短语以及与之相关的情感分数。使用情感词典可以对文本中的每个词进行情感打分,并根据打分结果对整个文本的情感进行统计和分析。 此外,nltk还提供了一些机器学习算法用于情感分析。我们可以使用这些算法从标记好的训练数据中学习情感分类器,然后将其应用于新的文本数据进行情感分类。这种方法需要一定的训练数据,并且需要进行特征提取和模型训练等步骤,但通常可以获得更高的准确性和泛化能力。 除了上述功能,nltk还提供了一些额外的辅助功能,如词干提取、词形还原、情感分析可视化等。这些功能可以进一步提升情感分析的效果和可视化分析的结果。 总结而言,Python nltk是一个支持情感分析的强大工具库,它提供了丰富的处理文本数据的方法和函数,包括预处理、情感打分和分类等功能。无论是基于词典的情感分析还是机器学习算法,我们都可以通过nltk来进行实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值