我一直在python中使用NLTK进行情感分析,它只有正,中性和否定类,如果我们要进行情感分析并且有一个数字可以显示一个句子可以是负数还是正数,该怎么办。有点将其视为回归问题。有没有经过培训的图书馆可以这样做?
答案 0 :(得分:2)
我知道执行此操作的几种方法:
from nltk.sentiment.vader import SentimentIntensityAnalyzer as sia
sentences = ['This is the worst lunch I ever had!',
'This is the best lunch I have ever had!!',
'I don\'t like this lunch.',
'I eat food for lunch.',
'Red is a color.',
'A really bad, horrible book, the plot was .']
hal = sia()
for sentence in sentences:
print(sentence)
ps = hal.polarity_scores(sentence)
for k in sorted(ps):
print('\t{}: {:>1.4}'.format(k, ps[k]), end=' ')
print()
示例输出:
This is the worst lunch I ever had!
compound: -0.6588 neg: 0.423 neu: 0.577 pos: 0.0
(请注意,这种方式需要您启动CoreNLP服务器的实例才能运行,例如:java -mx1g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -port 9000 -timeout 15000
)
from pycorenlp import StanfordCoreNLP
stanford = StanfordCoreNLP('http://localhost:9000')
for sentence in sentences:
print(sentence)
result = stanford.annotate(sentence,
properties={
'annotators': 'sentiment',
'outputFormat': 'json',
'timeout': '5000'
})
for s in result['sentences']:
score = (s['sentimentValue'], s['sentiment'])
print(f'\tScore: {score[0]}, Value: {score[1]}')
示例输出:
This is the worst lunch I ever had!
Score: 0, Value: Verynegative