1

我正在尝试使用基于词典的评分方法对文本进行一些情感分析。在阅读了堆栈溢出帖子后,我直接从http://analyzecore.com/2014/04/28/twitter-sentiment-analysis/借用了我的代码: R 情绪分析与字典中的短语

以下是关于我的数据集的一些总结:

> summary(data$text)
   Length     Class      Mode 
       30 character character 
> str(data$text)
 chr [1:30] "Hey everybody, are you guys free on Sunday for a game play + dinner afterwards? I'll reserve a"| __truncated__ ...

和我正在使用的代码:

require(plyr)  
require(stringr)
require(data.table)
score.sentiment = function(sentences, pos.words, neg.words, .progress='none')
{
  scores = laply(sentences, function(sentence, pos.words, neg.words) {

    sentence = gsub('[[:punct:]]', '', sentence)
    sentence = gsub('[[:cntrl:]]', '', sentence)
    sentence = gsub('\\d+', '', sentence)
    # and convert to lower case:
    sentence = tolower(sentence)

    # split into words. str_split is in the stringr package
    word.list = str_split(sentence, '\\s+')
    # sometimes a list() is one level of hierarchy too much
    words = unlist(word.list)

    # compare our words to the dictionaries of positive & negative terms
    pos.matches = match(words, pos.words)
    neg.matches = match(words, neg.words)

    pos.matches = !is.na(pos.matches)
    neg.matches = !is.na(neg.matches)

    # and conveniently enough, TRUE/FALSE will be treated as 1/0 by sum():
    score = (sum(pos.matches) - sum(neg.matches))

    return(score)
  } , pos.words, neg.words, .progress=.progress)

  scores.df = data.frame(score = scores, text = sentences)
  return(scores.df)
}

我正在使用 Bing Liu 的意见词典,并将它们加载为:

pos_BL = read.table(file = 'positive-words.txt', stringsAsFactors = F)
neg_BL = read.table(file = 'negative-words.txt', stringsAsFactors = F)

这是我用来通过评分函数运行数据和字典的代码:

score_result = score.sentiment(sentences = data$text, 
                               pos.words = pos_BL, 
                               neg.words = neg_BL, 
                               .progress= 'text')

但是,无论我做什么,我的 30 根琴弦都只能得到 0 分。(输出总结见下表):

> table(score_result$score)
 0 
30 

我不知道在哪里修复(在此处发布此问题之前,我确实在自己的代码中发现了许多错误)。任何帮助深表感谢!

4

2 回答 2

0

一个例子:

list=list(a='This place is awesome', b='I failed in the exam')
lapply(list, polarity)
于 2016-06-22T09:22:50.017 回答
0

您必须注意不要将表格或 df 而不是向量作为函数 'score.sentiment' 的 'pos.words' 和 'neg.words' 参数引入。在这种情况下,它将花费更长的时间并且不返回任何结果。尝试这样的事情:

score_result = score.sentiment(sentences = data$text, 
                               pos.words = as.character(pos_BL[ , 1]), 
                               neg.words = as.character(neg_BL[ , 1]), 
                               .progress= 'text')

也许'as.character()'函数不是必需的。

于 2020-04-17T15:33:25.300 回答