Okay, modifying the script to color the sentences of the text based on their sentiment is more complex, as it requires rendering the colored text in a suitable output format (like HTML). R isn't ideally suited for directly displaying colored text in a console. However, I can create an HTML file where each sentence is wrapped in a <span> tag with a style that sets the text color based on sentiment.
Here's the updated R script:
# Install necessary packages (if you haven't already)
# install.packages("gutenbergr")
# install.packages("dplyr")
# install.packages("stringr")
# install.packages("syuzhet")
library(gutenbergr)
library(dplyr)
library(stringr)
library(syuzhet)
# Function to download, analyze, and colorize a book
colorize_book <- function(book_id, title, output_file = "colored_book.html") {
tryCatch({
# Download the book
book_text <- gutenberg_download(book_id)
if (nrow(book_text) == 0) {
stop(paste("Book with ID", book_id, "not found."))
}
# Convert to a single string, split into sentences
book_sentences <- book_text %>%
mutate(text = str_replace_all(text, "[[:punct:]]", "")) %>% # Remove punctuation
pull(text) %>%
paste(collapse = " ") %>%
strsplit("[.?!]") %>% # Split into sentences
unlist()
# Remove empty strings from sentences
book_sentences <- book_sentences[book_sentences != ""]
# Get sentiment scores
sentiment_scores <- get_sentiment(book_sentences, method = "syuzhet")
# Determine sentiment color based on score
sentiment_colors <- sapply(sentiment_scores, function(score) {
if (score > 0.5) {
"green" # Positive
} else if (score < -0.5) {
"red" # Negative
} else {
"black" # Neutral
}
})
# Create HTML content
html_content <- paste0("<html><body><h1>", title, "</h1>")
for (i in 1:length(book_sentences)) {
html_content <- paste0(html_content,
"<span style='color:", sentiment_colors[i], "'>",
book_sentences[i],
"</span> ")
}
html_content <- paste0(html_content, "</body></html>")
# Write HTML content to file
write(html_content, file = output_file)
cat("Colored book saved to", output_file, "\n")
}, error = function(e) {
cat("Error processing book ID", book_id, ":", e$message, "\n")
})
}
# Example Usage:
book_id <- 2701 # Moby Dick
title <- "Moby Dick"
colorize_book(book_id, title, output_file = "moby_dick_colored.html")
book_id <- 84 # Frankenstein
title <- "Frankenstein"
colorize_book(book_id, title, output_file = "frankenstein_colored.html")
Key changes and explanations:
colorize_book Function: This function now handles the entire process: downloading, sentiment analysis, color assignment, and HTML generation.