使用bigrams的情感分析

时间:2018-02-24 13:24:21

标签: python nltk stanford-nlp sentiment-analysis

所以我有一些评论,我试图将其归类为正面或负面。我正在尝试使用NLTK和Stanford coreNLP这样做。我能够在unigrams上做到这一点,但它不适用于bigrams。我为bigrams尝试了以下内容

def classifySentence(sen):
  wn_lem = WordNetLemmatizer()
  pos = 0
  neg = 0
  stop_words = set(stopwords.words('english'))
  filtered_review = [token for token in nltk.word_tokenize(sen) if not token in stop_words]


  for token in nltk.bigrams(filtered_review):
      #lemma = wn_lem.lemmatize(token)
      # print("lemma="+token)
      if len(wn.synsets(token))>0:
          synset = wn.synsets(token)[0]
          #print("synset.name="+synset.name())

          sent = swn.senti_synset(synset.name())

          #print("Sentiment of "+token+" "+str(sent))

          pos = pos + sent.pos_score()
          neg = neg + sent.neg_score()
          # print (token + "(pos_score): " + str(pos) +"\n")
          # print (token + "(neg_score): " + str(neg) +"\n")
  #print (filtered_review)
  JoinedTokens = ' '.join(wo for wo in filtered_review)
  return [JoinedTokens, pos, neg]

我想知道是否有人可以建议我这样做的方法。我想使用NLTK或者也可以使用stanfordcoreNLP。我也愿意使用其他python包,但只需要一些指导 我已经编写了一些使用它的代码,但它也没有用。我写的代码

def StanfordBigrams():
  nlp = StanfordCoreNLP('http://localhost:9000')
  operations = {'annotators': 'tokenize,lemma,pos,sentiment', 'outputFormat': 'json'}
  string = "not bad"
  tok = nltk.word_tokenize(string)
  bigrams = nltk.bigrams(tok)
  res = nlp.annotate(str(bigrams),operations)
  for s in res["sentences"]: 
          for token in s["tokens"]:
              print("Sentiment: "+str(s["sentiment"])+"SentimentValue: "+str(s["sentimentValue"]))
              print (token)

如果有人能指出我正确的方向,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

您是在训练情绪分类器,还是只是尝试使用它?从技术上讲,我怀疑你的错误是在wn.synset(bigram) - 我怀疑从nltk.bigrams返回的是一个可以传递到WordNet的词。

但是,更重要的是,你可能想把你的整个句子传递给情绪分类器 - 双胞胎并没有像SentiWordNet那样在他们身上注释情绪,而训练有素的情绪分类将会有一个句子上的句子比短片段容易得多。你应该能够从斯坦福大学的情感树中获得句子中某些一些的情感(仅与根部的情感值相比)。请参阅CoreNLP服务器的JSON输出上的sentimentTree字段。

相关问题