使用二元组进行情感分析

Sentiment analysis using bigrams

所以我有一些评论,我试图将其归类为正面或负面。我正在尝试使用 NLTK 和 Stanford coreNLP 来这样做。我可以在 unigrams 上做到这一点,但它不适用于 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)

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

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

但是,更重要的是,您可能希望将整个句子传递到一个情感分类器中——二元语法不会在 SentiWordNet 之类的东西上对它们进行情感注释,并且训练有素的情感分类器将有一个句子上的时间比短片段上的时间要容易得多。您应该能够从斯坦福的情感树中获得句子中 一些 的二元组的情感(相对于根部的情感值)。请参阅 CoreNLP 服务器 JSON 输出中的 sentimentTree 字段。