開始使用免費開始

情感分數

在《動物農莊》一書中,有三隻關鍵的豬推動了故事的發展:Napoleon、Snowball,以及 Squealer。整本書中,他們散播反叛的想法,並鼓動其他動物從農場主人 Mr. Jones 手中奪取農莊的掌控權。

請使用提到各豬隻名字的句子,判斷哪個角色與最負面的情感最相關。sentences tibble 包含《動物農莊》中各句子的資料。

本練習屬於課程

R 的自然語言處理入門

檢視課程

練習說明

  • 使用 grepl() 函式過濾只提到各豬隻名字的句子。
  • 使用 inner_join(),從 afinn 辭典合併情感分數。
  • 將結果彙總,對 score 欄位進行加總。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# 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))
}
編輯並執行程式碼