*仍然难倒*使用R与twitteR,plyr,stringr和RMySQL包的推文的情感分析

时间:2013-06-25 16:34:12

标签: r twitter

我正在关注R twitteR包的初学者教程,我遇到了障碍。 (教程URL:https://sites.google.com/site/miningtwitter/questions/sentiment/analysis

我不是通过第4节中详述的searchTwitter函数导入推文列表,而是从MySQL数据库导入推文的数据框。我可以很好地从MySQL导入推文,但是当我尝试执行时:

wine_txt = sapply(wine_tweets,function(x)x $ getText())

我收到错误:

x $ getText中的错误:$运算符对原子矢量无效

数据已经是data.frame形式,我随后又将它强制进入data.frame,以确保我仍然得到相同的错误。我在下面粘贴了我的完整代码,非常感谢任何帮助。

library(twitteR)
library(plyr)
library(stringr)
library(RMySQL)

tweets.con<-dbConnect(MySQL(),user="XXXXXXXX",password="XXXXXXXX",dbname="XXXXXXX",host="XXXXXXX")
wine_tweets<-dbGetQuery(tweets.con,"select `tweet_text` from `tweets` where `created_at` BETWEEN timestamp(DATE_SUB(NOW(), INTERVAL 11 MINUTE)) AND timestamp(NOW())")

# function score.sentiment
score.sentiment = function(sentences, pos.words, neg.words, .progress='none')
{
# Parameters
# sentences: vector of text to score
# pos.words: vector of words of postive sentiment
# neg.words: vector of words of negative sentiment
# .progress: passed to laply() to control of progress bar

# create simple array of scores with laply
scores = laply(sentences,
function(sentence, pos.words, neg.words)
{
  # remove punctuation
  sentence = gsub("[[:punct:]]", "", sentence)
  # remove control characters
  sentence = gsub("[[:cntrl:]]", "", sentence)
  # remove digits?
  sentence = gsub('\\d+', '', sentence)

  # define error handling function when trying tolower
  tryTolower = function(x)
  {
     # create missing value
     y = NA
     # tryCatch error
     try_error = tryCatch(tolower(x), error=function(e) e)
     # if not an error
     if (!inherits(try_error, "error"))
     y = tolower(x)
     # result
     return(y)
  }
  # use tryTolower with sapply 
  sentence = sapply(sentence, tryTolower)

  # split sentence into words with str_split (stringr package)
  word.list = str_split(sentence, "\\s+")
  words = unlist(word.list)

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

  # get the position of the matched term or NA
  # we just want a TRUE/FALSE
  pos.matches = !is.na(pos.matches)
  neg.matches = !is.na(neg.matches)

  # final score
  score = sum(pos.matches) - sum(neg.matches)
  return(score)
  }, pos.words, neg.words, .progress=.progress )

# data frame with scores for each sentence
scores.df = data.frame(text=sentences, score=scores)
return(scores.df)
}

# import positive and negative words
pos = readLines("/home/jgraab/R/scripts/positive_words.txt")
neg = readLines("/home/jgraab/R/scripts/negative_words.txt")
wine_txt = sapply(wine_tweets, function(x) x$getText())

1 个答案:

答案 0 :(得分:0)

$用于获取数据框(或列表等)的列,您无法使用它来应用函数。你想要像

这样的东西
getText(x)

那里。