Get startedGet started for free

Sentiment scores

In the book Animal Farm, three main pigs are responsible for the events of the book: Napoleon, Snowball, and Squealer. Throughout the book they are spreading thoughts of rebellion and encouraging the other animals to take over the farm from Mr. Jones - the owner of the farm.

Using the sentences that mention each pig, determine which character has the most negative sentiment associated with them. The sentences tibble contains a tibble of the sentences from the book Animal Farm.

This exercise is part of the course

Introduction to Natural Language Processing in R

View Course

Exercise instructions

  • Use the grepl() function to filter to sentences mentioning just the pigs name.
  • Using an inner_join(), join the sentiment score from the afinn lexicon.
  • Summarize the results by summing the score column.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Print the overall sentiment associated with each pig's sentences
for(name in c("napoleon", "snowball", "squealer")) {
  # Filter to the sentences mentioning the pig
  pig_sentences <- sentences[___(___, sentences$sentence), ]
  # Tokenize the text
  napoleon_tokens <- pig_sentences %>%
    unnest_tokens(output = "word", token = "words", input = sentence) %>%
    anti_join(stop_words)
  # Use afinn to find the overall sentiment score
  result <- napoleon_tokens %>% 
    inner_join(___("___")) %>%
    summarise(sentiment = ___(___))
  # Print the result
  print(paste0(name, ": ", result$sentiment))
}
Edit and Run Code