Example Qbit to predict the sentiment of sentences based on the bag-of-words methodology and the Bing sentiment dictionary.
library(dplyr)
library(tidyr)
library(tidytext)
library(SnowballC)
library(stopwords)
# See also https://smltar.com/stemming.html#how-to-stem-text-in-r
get_sentiments_stem <- function(dict) {
get_sentiments(dict) %>%
mutate(stem = wordStem(word)) %>%
distinct(stem, sentiment)
}
sentiment_list <- function(sentence) {
tibble(text = sentence) %>%
unnest_tokens(word, text) %>%
anti_join(get_stopwords()) %>%
mutate(stem = wordStem(word)) %>%
left_join(get_sentiments_stem("bing"), by = "stem")
}
sentiment_score <- function(sentence) {
sentiment_list(sentence) %>%
mutate(score = ifelse(sentiment == "positive", 1, -1))
}
polarity <- function(sentence) {
df <- sentiment_score(sentence)
sum(df$score, na.rm = TRUE) / sum(abs(df$score), na.rm = TRUE)
}
sentence_positive <- "I'm so happy that the sun is shining and the birds singing!"
sentence_negative <- "I had the worst day of my live. I'm very sad and depressed."
sentiment_list(sentence_positive)
sentiment_list(sentence_negative)
sentiment_score(sentence_positive)
sentiment_score(sentence_negative)
polarity(sentence_positive)
polarity(sentence_negative)
Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.