在python中使用nltk Sentiwordnet

2024-06-24 13:49:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python NLTK对twitter数据进行情绪分析。我需要一本字典,里面有单词的+ve和-ve极性。我读了很多关于sentiwordnet的文章,但是当我在我的项目中使用它时,它并不能提供高效和快速的结果。我想我用得不对。有人能告诉我正确的使用方法吗?以下是我到目前为止所做的步骤:

  1. tweets的标记化
  2. 代币词性标注
  3. 将每个标签传递给sentinet

我使用nltk包进行标记和标记。下面是我的代码:

import nltk
from nltk.stem import *
from nltk.corpus import sentiwordnet as swn

tokens=nltk.word_tokenize(row) #for tokenization, row is line of a file in which tweets are saved.
tagged=nltk.pos_tag(tokens) #for POSTagging

for i in range(0,len(tagged)):
     if 'NN' in tagged[i][1] and len(swn.senti_synsets(tagged[i][0],'n'))>0:
            pscore+=(list(swn.senti_synsets(tagged[i][0],'n'))[0]).pos_score() #positive score of a word
            nscore+=(list(swn.senti_synsets(tagged[i][0],'n'))[0]).neg_score()  #negative score of a word
    elif 'VB' in tagged[i][1] and len(swn.senti_synsets(tagged[i][0],'v'))>0:
           pscore+=(list(swn.senti_synsets(tagged[i][0],'v'))[0]).pos_score()
           nscore+=(list(swn.senti_synsets(tagged[i][0],'v'))[0]).neg_score()
    elif 'JJ' in tagged[i][1] and len(swn.senti_synsets(tagged[i][0],'a'))>0:
           pscore+=(list(swn.senti_synsets(tagged[i][0],'a'))[0]).pos_score()
           nscore+=(list(swn.senti_synsets(tagged[i][0],'a'))[0]).neg_score()
    elif 'RB' in tagged[i][1] and len(swn.senti_synsets(tagged[i][0],'r'))>0:
           pscore+=(list(swn.senti_synsets(tagged[i][0],'r'))[0]).pos_score()
           nscore+=(list(swn.senti_synsets(tagged[i][0],'r'))[0]).neg_score()

最后,我将计算有多少条tweets是正面的,有多少条tweets是负面的。 我错在哪里?我该怎么用?还有没有其他类似的词典,容易使用呢?


Tags: andinposlentweetslistscorenltk
2条回答

是的,你还可以使用其他词汇。你可以在这里找到一小串词典:http://sentiment.christopherpotts.net/lexicons.html#resources 刘冰的意见词典似乎很容易使用。

除了链接到这些词汇外,这个网站是一个非常好的情绪分析教程。

计算情绪

alist = [all_tokens_in_doc]

totalScore = 0

count_words_included = 0

for word in all_words_in_comment:

    synset_forms = list(swn.senti_synsets(word[0], word[1]))

    if not synset_forms:

        continue

    synset = synset_forms[0] 

    totalScore = totalScore + synset.pos_score() - synset.neg_score()

    count_words_included = count_words_included +1

final_dec = ''

if count_words_included == 0:

    final_dec = 'N/A'

elif totalScore == 0:

    final_dec = 'Neu'        

elif totalScore/count_words_included < 0:

    final_dec = 'Neg'

elif totalScore/count_words_included > 0:

    final_dec = 'Pos'

return final_dec

相关问题 更多 >