I'm doing sentiment analysis with a list of words correspond to a score range from 1-8 instead of counting positive word as 1 and negative word as -1.
here is part of the list:
word score
laughter 8.50
happiness 8.44
love 8.42
happy 8.30
laughed 8.26
laugh 8.22
How can I apply this list to the sentiment.score function so that I will have the score * word count instead of word count only
score.sentiment = function(sentences, new_list, .progress='none')
{
require(plyr)
require(stringr)
# we got a vector of sentences. plyr will handle a list or a vector as an "l" for us
# we want a simple array of scores back, so we use "l" + "a" + "ply" = laply:
scores = laply(sentences, function(sentence, terms) {
# clean up sentences with R's regex-driven global substitute, gsub():
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
words.matches = match(words, terms)
# match() returns the position of the matched term or NA
# we just want a TRUE/FALSE:
words.matches = !is.na(words.matches)
# how to count the score??
score = ?????
return(score)
}, terms, .progress=.progress )
scores.df = data.frame(score=scores, text=sentences)
return(scores.df)
}
Here's an example:
df <- read.table(header=TRUE, text="word score
laughter 8.50
happiness 8.44
love 8.42
happy 8.30
laughed 8.26
laugh 8.22")
sentence <- "I love happiness"
words <- strsplit(sentence, "\\s+")[[1]]
score <- sum(df$score[match(words, df$word)], na.rm = TRUE)
print(score)
# [1] 16.86
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.