R Script for Gutenberg Book Analysis with Visualization
This script demonstrates how to download books from Project Gutenberg and perform data visualization. The script covers downloading multiple books, processing text data, and creating various visualizations.
Required Packages Installation
First, let's install the necessary packages:
r
# Install required packages if not already installed
if (!require("gutenbergr")) install.packages("gutenbergr")
if (!require("tidyverse")) install.packages("tidyverse")
if (!require("tidytext")) install.packages("tidytext")
if (!require("shutterplot")) install.packages("shutterplot")
if (!require("stringr")) install.packages("stringr")
if (!require("ggplot2")) install.packages("ggplot2")
# Load the packages
library(gutenbergr)
library(tidyverse)
library(tidytext)
library(shutterplot)
library(stringr)
library(ggplot2)
Downloading Books from Project Gutenberg
Now, let's download some classic books from Project Gutenberg:
r
# Let's find some Jane Austen books
austen_books <- gutenberg_works(author == "Austen, Jane")
print(austen_books)
# Download multiple Jane Austen books
austen_text <- gutenberg_download(
c(105, 161, 1342), # Persuasion, Sense and Sensibility, Pride and Prejudice
meta_fields = "title"
)
# Let's also download Wuthering Heights and Jane Eyre for comparison
bronte_text <- gutenberg_download(
c(768, 1260), # Wuthering Heights, Jane Eyre
meta_fields = "title"
)
# Combine all books into one dataset
all_books <- bind_rows(austen_text, bronte_text)
Text Processing
Next, we'll process the text to prepare for analysis:
r
# Convert to tidy text format (one word per row)
tidy_books <- all_books %>%
unnest_tokens(word, text) %>%
anti_join(stop_words) # Remove common stop words
# Get word counts per book
word_counts <- tidy_books %>%
count(title, word, sort = TRUE) %>%
group_by(title) %>%
mutate(proportion = n / sum(n)) %>%
ungroup()
# Calculate sentences per book
sentences_per_book <- all_books %>%
group_by(title) %>%
summarize(
total_lines = n(),
text_combined = paste(text, collapse = " "),
total_chars = nchar(text_combined),
sentence_count = str_count(text_combined, "[.!?]\\s+[A-Z]|[.!?]$"),
avg_sentence_length = total_chars / sentence_count
)
Creating Basic Text Analysis Plots
Let's create some basic visualizations of our text data:
r
# Plot word frequencies
word_counts %>%
filter(n > 100) %>%
ggplot(aes(n, proportion, color = title)) +
geom_point() +
scale_x_log10() +
scale_y_log10() +
labs(title = "Word Frequencies Across Books",
x = "Word Count (log scale)",
y = "Proportion (log scale)") +
theme_minimal()
# Plot most common words per book
word_counts %>%
group_by(title) %>%
top_n(10, n) %>%
ungroup() %>%
ggplot(aes(reorder_within(word, n, title), n, fill = title)) +
geom_col(show.legend = FALSE) +
facet_wrap(~ title, scales = "free_y") +
coord_flip() +
scale_x_reordered() +
labs(title = "Top 10 Words in Each Book",
x = NULL,
y = "Word Count") +
theme_minimal()
Creating Shutter Plots for Text Analysis Metrics
Now, let's use the shutterplot package to visualize relationships between text metrics:
r
# First, let's create a dataframe with various text metrics
text_metrics <- all_books %>%
group_by(gutenberg_id, title) %>%
summarize(
avg_line_length = mean(nchar(text), na.rm = TRUE),
max_line_length = max(nchar(text), na.rm = TRUE),
total_lines = n(),
empty_lines = sum(nchar(text) == 0),
text_combined = paste(text, collapse = " "),
total_chars = nchar(text_combined),
unique_words = n_distinct(str_extract_all(tolower(text_combined), "\\w+")[[1]]),
sentence_count = str_count(text_combined, "[.!?]\\s+[A-Z]|[.!?]$"),
avg_sentence_length = total_chars / sentence_count,
avg_word_length = mean(nchar(str_extract_all(tolower(text_combined), "\\w+")[[1]]), na.rm = TRUE)
) %>%
ungroup()
# Create a shutter plot comparing sentence length to word length
shutterplot(
text_metrics$avg_sentence_length,
text_metrics$avg_word_length,
main = "Relationship Between Sentence Length and Word Length",
xlab = "Average Sentence Length (characters)",
ylab = "Average Word Length (characters)",
colOfPoints = "darkblue"
)
# Create a shutter plot comparing line count to unique word count
shutterplot(
text_metrics$total_lines,
text_metrics$unique_words,
main = "Relationship Between Book Length and Vocabulary Size",
xlab = "Total Lines in Book",
ylab = "Unique Words Used",
colOfPoints = "darkred"
)
# Create a summary of our metrics
shutterplotsummary(text_metrics$avg_sentence_length, text_metrics$avg_word_length)
Word Frequency Analysis with Shutter Plots
Let's analyze word frequencies across books using shutter plots:
r
# Create a wide format dataframe of word frequencies for the most common words
common_words <- word_counts %>%
group_by(word) %>%
summarize(total = sum(n)) %>%
arrange(desc(total)) %>%
head(100) %>%
pull(word)
word_freq_wide <- word_counts %>%
filter(word %in% common_words) %>%
pivot_wider(
id_cols = word,
names_from = title,
values_from = proportion,
values_fill = 0
)
# Compare word usage between Pride and Prejudice and Jane Eyre
shutterplot(
word_freq_wide$`Pride and Prejudice`,
word_freq_wide$`Jane Eyre`,
main = "Word Usage Comparison",
xlab = "Pride and Prejudice",
ylab = "Jane Eyre",
colOfPoints = "purple"
)
# Add a summary of the comparison
shutterplotsummary(
word_freq_wide$`Pride and Prejudice`,
word_freq_wide$`Jane Eyre`
)
Exploring Different Types of Plots
Finally, let's create some additional plots using basic R plotting functions:
r
# Visualize sentence length distribution with a histogram
sentences_per_book %>%
ggplot(aes(x = title, y = avg_sentence_length, fill = title)) +
geom_col() +
labs(title = "Average Sentence Length by Book",
x = NULL,
y = "Average Sentence Length (characters)") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
# Create a summary7plot for sentence lengths
summary7plot(text_metrics$avg_sentence_length)
# Compare book lengths
text_metrics %>%
ggplot(aes(x = reorder(title, total_lines), y = total_lines, fill = title)) +
geom_col() +
labs(title = "Book Length Comparison",
x = NULL,
y = "Total Lines") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
Complete Analysis Function
Here's a reusable function that performs the entire analysis:
r
analyze_gutenberg_books <- function(book_ids, book_titles = NULL) {
# Download books
books <- gutenberg_download(book_ids, meta_fields = "title")
# Process text
tidy_books <- books %>%
unnest_tokens(word, text) %>%
anti_join(stop_words)
# Get word counts
word_counts <- tidy_books %>%
count(title, word, sort = TRUE) %>%
group_by(title) %>%
mutate(proportion = n / sum(n)) %>%
ungroup()
# Calculate metrics
text_metrics <- books %>%
group_by(gutenberg_id, title) %>%
summarize(
avg_line_length = mean(nchar(text), na.rm = TRUE),
unique_words = n_distinct(str_extract_all(tolower(paste(text, collapse = " ")), "\\w+")[[1]])
)
# Create shutterplot if there are at least 2 books
if(n_distinct(text_metrics$title) >= 2) {
metrics_wide <- text_metrics %>%
select(title, avg_line_length) %>%
pivot_wider(names_from = title, values_from = avg_line_length)
col_names <- colnames(metrics_wide)
shutterplot(
metrics_wide[[col_names[1]]],
metrics_wide[[col_names[2]]],
main = "Text Metrics Comparison",
xlab = col_names[1],
ylab = col_names[2]
)
}
return(list(
books = books,
tidy_books = tidy_books,
word_counts = word_counts,
text_metrics = text_metrics
))
}
# Example usage
results <- analyze_gutenberg_books(c(1342, 768)) # Pride and Prejudice, Wuthering Heights
This script provides a comprehensive analysis of books from Project Gutenberg using both text mining techniques and visualization with the shutterplot package. You can customize it further based on specific analytical needs.
User
Continue the script
Assistant
Continuing the R Script for Gutenberg Book Analysis
Sentiment Analysis
Let's enhance our analysis with sentiment analysis to explore emotional content:
r
# Install additional packages for sentiment analysis
if (!require("textdata")) install.packages("textdata")
library(textdata)
# Get sentiment lexicons
nrc_sentiments <- get_sentiments("nrc")
bing_sentiments <- get_sentiments("bing")
afinn_sentiments <- get_sentiments("afinn")
# Analyze sentiment across books
book_sentiments <- tidy_books %>%
inner_join(nrc_sentiments) %>%
count(title, sentiment) %>%
group_by(title) %>%
mutate(proportion = n / sum(n)) %>%
ungroup()
# Visualize sentiments across books
book_sentiments %>%
ggplot(aes(sentiment, proportion, fill = title)) +
geom_col(position = "dodge") +
coord_flip() +
labs(title = "Sentiment Proportions Across Books",
x = "Sentiment",
y = "Proportion") +
theme_minimal()
# Create a shutter plot comparing positive vs negative sentiments
book_bing <- tidy_books %>%
inner_join(bing_sentiments) %>%
count(title, sentiment) %>%
spread(sentiment, n, fill = 0)
shutterplot(
book_bing$negative,
book_bing$positive,
main = "Positive vs Negative Sentiment Comparison",
xlab = "Negative Word Count",
ylab = "Positive Word Count",
colOfPoints = "forestgreen"
)
# Analyze sentiment flow throughout the books
sentiment_flow <- all_books %>%
group_by(title) %>%
mutate(page_number = row_number() %/% 80) %>% # Approximate page breaks
unnest_tokens(word, text) %>%
inner_join(afinn_sentiments) %>%
group_by(title, page_number) %>%
summarize(sentiment_score = sum(value)) %>%
ungroup()
# Plot sentiment flow
sentiment_flow %>%
ggplot(aes(page_number, sentiment_score, color = title)) +
geom_line(size = 1) +
geom_smooth(method = "loess", se = FALSE, linetype = "dashed") +
labs(title = "Emotional Arc Throughout Books",
x = "Page Number (approx.)",
y = "Sentiment Score") +
theme_minimal()
User
No, have it use the syuzhet library to produce graphs
Assistant
R Script for Gutenberg Book Analysis Using Syuzhet
This script demonstrates how to download books from Project Gutenberg and perform sentiment analysis using the syuzhet package. The script will analyze text data and create various visualizations of sentiment and emotional arcs.
Required Packages Installation
First, let's install and load the necessary packages:
r
# Install required packages if not already installed
if (!require("gutenbergr")) install.packages("gutenbergr")
if (!require("tidyverse")) install.packages("tidyverse")
if (!require("tidytext")) install.packages("tidytext")
if (!require("syuzhet")) install.packages("syuzhet")
if (!require("wordcloud")) install.packages("wordcloud")
if (!require("reshape2")) install.packages("reshape2")
if (!require("gridExtra")) install.packages("gridExtra")
# Load the packages
library(gutenbergr)
library(tidyverse)
library(tidytext)
library(syuzhet)
library(wordcloud)
library(reshape2)
library(gridExtra)
Downloading Books from Project Gutenberg
Now, let's download some classic books from Project Gutenberg:
r
# Find some Jane Austen books
austen_books <- gutenberg_works(author == "Austen, Jane")
print(austen_books)
# Download multiple Jane Austen books
austen_text <- gutenberg_download(
c(105, 161, 1342), # Persuasion, Sense and Sensibility, Pride and Prejudice
meta_fields = "title"
)
# Let's also download Wuthering Heights and Jane Eyre for comparison
bronte_text <- gutenberg_download(
c(768, 1260), # Wuthering Heights, Jane Eyre
meta_fields = "title"
)
# Combine all books into one dataset
all_books <- bind_rows(austen_text, bronte_text)
Processing Text with Syuzhet
Let's process each book to prepare for sentiment analysis:
User
How to download gutenberg file as txt doc using the gutenbergr package
Assistant
Downloading Gutenberg Files as Text Documents Using the gutenbergr Package
The gutenbergr package allows you to download books from Project Gutenberg directly into R. While the package doesn't save files directly as .txt files by default, you can easily accomplish this with a few additional steps.
Installing and Loading the Package
First, make sure you have the gutenbergr package installed and loaded:
r
# Install if needed
install.packages("gutenbergr")
# Load the package
library(gutenbergr)
library(dplyr) # For data manipulation
Finding the Gutenberg ID
Before downloading, you need to know the ID of the book you want to download:
r
# Search by title
gutenberg_works(title == "Wuthering Heights")
# Search by author
gutenberg_works(author == "Austen, Jane")
# Browse all English works
gutenberg_metadata %>%
filter(language == "en", has_text == TRUE)
Downloading the Book
The gutenberg_download() function brings the text into R as a data frame:
r
# Download a single book by ID
book <- gutenberg_download(768) # 768 is Wuthering Heights
# Download multiple books at once
books <- gutenberg_download(c(1342, 84)) # Pride and Prejudice and Frankenstein
# Include metadata like title in the result
book_with_meta <- gutenberg_download(1342, meta_fields = "title")
Saving as a Text File
To save the downloaded book as a text file:
r
# Method 1: Basic approach for a single book
writeLines(book$text, "wuthering_heights.txt")
# Method 2: For multiple books or with dynamic filenames
books <- gutenberg_download(c(1342, 84), meta_fields = "title")
# Create safe filenames from titles
books %>%
group_by(gutenberg_id, title) %>%
summarize(full_text = paste(text, collapse = "\n")) %>%
rowwise() %>%
mutate(
safe_filename = gsub("[^a-zA-Z0-9]", "_", title),
filepath = paste0(safe_filename, ".txt")
) %>%
rowwise() %>%
do({
writeLines(.$full_text, .$filepath)
.
})
Bigram Analysis and Word Networks
Let's explore word relationships and co-occurrences:
r
# Extract bigrams from texts
book_bigrams <- all_books %>%
group_by(title) %>%
unnest_tokens(bigram, text, token = "ngrams", n = 2) %>%
ungroup()
# Separate bigrams into two words
bigrams_separated <- book_bigrams %>%
separate(bigram, c("word1", "word2"), sep = " ")
# Remove bigrams containing stop words
bigrams_filtered <- bigrams_separated %>%
filter(!word1 %in% stop_words$word) %>%
filter(!word2 %in% stop_words$word)
# Count bigram frequencies
bigram_counts <- bigrams_filtered %>%
count(title, word1, word2, sort = TRUE)
# Visualize top bigrams for each book
bigram_counts %>%
group_by(title) %>%
top_n(10, n) %>%
ungroup() %>%
mutate(bigram = paste(word1, word2, sep = " ")) %>%
ggplot(aes(reorder_within(bigram, n, title), n, fill = title)) +
geom_col(show.legend = FALSE) +
facet_wrap(~ title, scales = "free_y") +
coord_flip() +
scale_x_reordered() +
labs(title = "Top Word Pairs in Each Book",
x = NULL,
y = "Count") +
theme_minimal()
# Create a network visualization for Pride and Prejudice
if (!require("igraph")) install.packages("igraph")
if (!require("ggraph")) install.packages("ggraph")
library(igraph)
library(ggraph)
# Filter for a specific book and create network
pride_network <- bigram_counts %>%
filter(title == "Pride and Prejudice") %>%
filter(n > 5) %>%
graph_from_data_frame()
# Plot the network
set.seed(42)
ggraph(pride_network, layout = "fr") +
geom_edge_link(aes(edge_alpha = n), show.legend = FALSE) +
geom_node_point(color = "lightblue", size = 5) +
geom_node_text(aes(label = name), repel = TRUE) +
labs(title = "Word Network in Pride and Prejudice") +
theme_void()
Topic Modeling
Let's use topic modeling to discover themes across books:
r
# Install and load required packages
if (!require("topicmodels")) install.packages("topicmodels")
library(topicmodels)
# Create document-term matrix
books_dtm <- tidy_books %>%
count(title, word) %>%
cast_dtm(title, word, n)
# Perform LDA (Latent Dirichlet Allocation)
books_lda <- LDA(books_dtm, k = 5, control = list(seed = 1234))
# Extract topics
book_topics <- tidy(books_lda, matrix = "beta")
# Get top terms per topic
top_terms <- book_topics %>%
group_by(topic) %>%
top_n(10, beta) %>%
ungroup() %>%
arrange(topic, -beta)
# Visualize top terms by topic
top_terms %>%
mutate(term = reorder_within(term, beta, topic)) %>%
ggplot(aes(term, beta, fill = factor(topic))) +
geom_col(show.legend = FALSE) +
facet_wrap(~ topic, scales = "free_y") +
coord_flip() +
scale_x_reordered() +
labs(title = "Top Terms by Topic",
x = NULL,
y = "Beta") +
theme_minimal()
# Get book-topic probabilities
book_gamma <- tidy(books_lda, matrix = "gamma")
# Visualize book-topic distribution
book_gamma %>%
mutate(title = reorder(document, gamma * topic)) %>%
ggplot(aes(factor(topic), gamma, fill = factor(topic))) +
geom_col() +
facet_wrap(~ document) +
labs(title = "Topic Distribution Across Books",
x = "Topic",
y = "Gamma") +
theme_minimal() +
theme(legend.position = "none")
# Create a topic correlation shutterplot
topic_corr <- book_gamma %>%
spread(topic, gamma) %>%
select(-document)
shutterplot(
topic_corr$`1`,
topic_corr$`2`,
main = "Topic Correlation",
xlab = "Topic 1 Weight",
ylab = "Topic 2 Weight",
colOfPoints = "orangered"
)
Readability Metrics and Text Complexity
Let's analyze the readability and complexity of texts:
# Function to process a single book
analyze_book_sentiment <- function(book_text, book_title) {
# Combine all text into a single string
text_string <- paste(book_text$text, collapse = " ")
# Get sentences using syuzhet's function
sentences <- get_sentences(text_string)
# Calculate sentiment using different methods
syuzhet_vector <- get_sentiment(sentences, method = "syuzhet")
bing_vector <- get_sentiment(sentences, method = "bing")
afinn_vector <- get_sentiment(sentences, method = "afinn")
nrc_vector <- get_sentiment(sentences, method = "nrc")
# Get emotions using the NRC lexicon
nrc_data <- get_nrc_sentiment(sentences)
# Return results as a list
return(list(
title = book_title,
sentences = sentences,
sentiment = list(
syuzhet = syuzhet_vector,
bing = bing_vector,
afinn = afinn_vector,
nrc = nrc_vector
),
emotions = nrc_data
))
}
# Process each book
book_sentiments <- list()
for (title in unique(all_books$title)) {
book_text <- all_books %>% filter(title == !!title)
book_sentiments[[title]] <- analyze_book_sentiment(book_text, title)
# Print progress
cat("Processed:", title, "\n")
}
Creating Basic Sentiment Plots with Syuzhet
Now, let's create basic sentiment plots for each book:
r
# Create a simple plot for each book
for (title in names(book_sentiments)) {
# Get sentiment data
sentiment_data <- book_sentiments[[title]]
# Create a simple plot using syuzhet's function
cat("Creating simple plot for:", title, "\n")
png(paste0("simple_plot_", gsub(" ", "_", title), ".png"),
width = 800, height = 500)
simple_plot(
sentiment_data$sentiment$syuzhet,
title = paste("Emotional Arc for", title),
window_size = 0.1
)
dev.off()
}
# Create a more detailed plot with rolling means
for (title in names(book_sentiments)) {
# Get sentiment data
sentiment_data <- book_sentiments[[title]]
# Calculate rolling mean for smoother plot
sentence_count <- length(sentiment_data$sentiment$syuzhet)
# Plot with rolling mean
cat("Creating detailed plot for:", title, "\n")
png(paste0("detailed_plot_", gsub(" ", "_", title), ".png"),
width = 800, height = 500)
plot(
sentiment_data$sentiment$syuzhet,
type = "l",
main = paste("Emotional Arc for", title),
xlab = "Narrative Time",
ylab = "Emotional Valence",
col = "gray"
)
# Add smoother line with moving average
lines(
rollmean(sentiment_data$sentiment$syuzhet, k = max(3, floor(sentence_count/100)),
fill = "extend"),
col = "blue",
lwd = 2
)
# Add a legend
legend("topright",
legend = c("Raw Sentiment", "Moving Average"),
col = c("gray", "blue"),
lty = 1,
lwd = c(1, 2))
dev.off()
}
Creating Transformed Sentiment Plots
Let's create transformed sentiment plots that show the overall narrative arc:
r
# Create DCT transformation plots
for (title in names(book_sentiments)) {
# Get sentiment data
sentiment_data <- book_sentiments[[title]]
# Calculate DCT transformation
dct_values <- get_dct_transform(
sentiment_data$sentiment$syuzhet,
low_pass_size = 5, # Keep the 5 most significant components
x_reverse_len = 100, # Return 100 values
scale_vals = TRUE, # Scale the values
scale_range = FALSE # Don't scale to -1 to 1 range
)
# Plot the DCT transformation
cat("Creating DCT plot for:", title, "\n")
png(paste0("dct_plot_", gsub(" ", "_", title), ".png"),
width = 800, height = 500)
plot(
dct_values,
type = "l",
main = paste("Narrative Arc for", title, "(DCT Method)"),
xlab = "Narrative Time",
ylab = "Emotional Valence",
col = "red",
lwd = 2
)
dev.off()
# Create percentage-based values plot (another way to view the arc)
percent_vals <- get_percentage_values(
sentiment_data$sentiment$syuzhet,
bins = 20 # Divide into 20 equal parts
)
# Plot the percentage values
cat("Creating percentage plot for:", title, "\n")
png(paste0("percentage_plot_", gsub(" ", "_", title), ".png"),
width = 800, height = 500)
plot(
percent_vals,
type = "l",
main = paste("Narrative Arc for", title, "(Percentage Method)"),
xlab = "Narrative Time",
ylab = "Emotional Valence",
col = "darkgreen",
lwd = 2
)
dev.off()
}
Comparing Different Sentiment Methods
Let's compare the different sentiment methods for each book:
r
# Compare different sentiment methods
for (title in names(book_sentiments)) {
# Get sentiment data
sentiment_data <- book_sentiments[[title]]
# Calculate percentage values for each sentiment method
syuzhet_percent <- get_percentage_values(sentiment_data$sentiment$syuzhet, bins = 20)
bing_percent <- get_percentage_values(sentiment_data$sentiment$bing, bins = 20)
afinn_percent <- get_percentage_values(sentiment_data$sentiment$afinn, bins = 20)
# Plot comparison
cat("Creating comparison plot for:", title, "\n")
png(paste0("comparison_plot_", gsub(" ", "_", title), ".png"),
width = 800, height = 500)
plot(
syuzhet_percent,
type = "l",
main = paste("Comparison of Sentiment Methods for", title),
xlab = "Narrative Time",
ylab = "Emotional Valence",
col = "red",
lwd = 2,
ylim = c(min(c(syuzhet_percent, bing_percent, afinn_percent)) - 0.1,
max(c(syuzhet_percent, bing_percent, afinn_percent)) + 0.1)
)
lines(bing_percent, col = "blue", lwd = 2)
lines(afinn_percent, col = "green", lwd = 2)
# Add a legend
legend("topright",
legend = c("Syuzhet", "Bing", "Afinn"),
col = c("red", "blue", "green"),
lty = 1,
lwd = 2)
dev.off()
}
Emotion Analysis with NRC Lexicon
Now, let's analyze and visualize the emotions in each book:
r
# Analyze emotions for each book
for (title in names(book_sentiments)) {
# Get emotion data
emotion_data <- book_sentiments[[title]]$emotions
# Calculate percentage of each emotion
emotion_percentage <- colSums(emotion_data) / nrow(emotion_data) * 100
# Create a bar plot of emotions
cat("Creating emotion bar plot for:", title, "\n")
png(paste0("emotion_barplot_", gsub(" ", "_", title), ".png"),
width = 800, height = 500)
barplot(
emotion_percentage,
main = paste("Emotion Distribution in", title),
col = rainbow(10),
las = 2,
cex.names = 0.8,
ylim = c(0, max(emotion_percentage) * 1.2)
)
dev.off()
# Create a pie chart of positive vs negative sentiment
sentiment_pie <- c(
Positive = emotion_percentage["positive"],
Negative = emotion_percentage["negative"]
)
cat("Creating sentiment pie chart for:", title, "\n")
png(paste0("sentiment_pie_", gsub(" ", "_", title), ".png"),
width = 600, height = 600)
pie(
sentiment_pie,
main = paste("Sentiment Distribution in", title),
col = c("green", "red"),
labels = paste0(names(sentiment_pie), " (", round(sentiment_pie, 1), "%)"),
border = "white"
)
dev.off()
# Create a word cloud of emotions
# First, prepare data for word cloud
emotion_names <- names(emotion_percentage)[1:8] # Exclude positive/negative
emotion_values <- emotion_percentage[1:8]
# Create a data frame for the word cloud
emotion_df <- data.frame(
word = emotion_names,
freq = emotion_values
)
cat("Creating emotion word cloud for:", title, "\n")
png(paste0("emotion_wordcloud_", gsub(" ", "_", title), ".png"),
width = 800, height = 800)
wordcloud(
words = emotion_df$word,
freq = emotion_df$freq,
min.freq = 0,
scale = c(4, 0.5),
colors = brewer.pal(8, "Dark2"),
random.order = FALSE,
rot.per = 0,
main = paste("Emotions in", title)
)
dev.off()
}
Creating Emotion Flow Graphs
Let's visualize how emotions change throughout each book:
r
# Analyze emotion flow for each book
for (title in names(book_sentiments)) {
# Get emotion data and sentences
emotion_data <- book_sentiments[[title]]$emotions
sentences <- book_sentiments[[title]]$sentences
# Create chunks (pseudo-chapters) for analysis
chunk_size <- max(10, floor(length(sentences) / 20)) # At least 10 sentences per chunk
n_chunks <- floor(length(sentences) / chunk_size)
# Calculate average emotion per chunk
emotion_flow <- matrix(0, nrow = n_chunks, ncol = 8) # 8 emotions
colnames(emotion_flow) <- names(emotion_data)[1:8] # Emotion names
for (i in 1:n_chunks) {
start_idx <- (i - 1) * chunk_size + 1
end_idx <- min(i * chunk_size, length(sentences))
emotion_flow[i, ] <- colMeans(emotion_data[start_idx:end_idx, 1:8])
}
# Convert to data frame for plotting
emotion_flow_df <- as.data.frame(emotion_flow)
emotion_flow_df$chunk <- 1:n_chunks
# Reshape for plotting
emotion_flow_long <- melt(emotion_flow_df, id.vars = "chunk",
variable.name = "emotion", value.name = "intensity")
# Plot emotion flow
cat("Creating emotion flow plot for:", title, "\n")
png(paste0("emotion_flow_", gsub(" ", "_", title), ".png"),
width = 1000, height = 600)
ggplot(emotion_flow_long, aes(x = chunk, y = intensity, color = emotion, group = emotion)) +
geom_line(size = 1) +
geom_smooth(method = "loess", se = FALSE, span = 0.3, size = 1.2) +
scale_color_brewer(palette = "Set1") +
labs(
title = paste("Emotion Flow Throughout", title),
x = "Narrative Progression (Chunks)",
y = "Emotion Intensity",
color = "Emotion"
) +
theme_minimal() +
theme(
plot.title = element_text(size = 16, face = "bold"),
legend.position = "right"
)
dev.off()
}
Comparison Between Books
Finally, let's compare the emotional content between books:
r
# Prepare data for comparison
emotion_comparison <- data.frame(
book = character(),
emotion = character(),
percentage = numeric(),
stringsAsFactors = FALSE
)
for (title in names(book_sentiments)) {
# Get emotion data
emotion_data <- book_sentiments[[title]]$emotions
# Calculate percentage of each emotion
emotion_percentage <- colSums(emotion_data) / nrow(emotion_data) * 100
# Add to comparison data frame
for (emotion_name in names(emotion_percentage)) {
emotion_comparison <- rbind(
emotion_comparison,
data.frame(
book = title,
emotion = emotion_name,
percentage = emotion_percentage[emotion_name],
stringsAsFactors = FALSE
)
)
}
}
# Create comparison bar chart
cat("Creating emotion comparison plot between books\n")
png("emotion_comparison_books.png", width = 1200, height = 800)
ggplot(emotion_comparison, aes(x = emotion, y = percentage, fill = book)) +
geom_bar(stat = "identity", position = "
Complete Example
Here's a complete function to download and save a book as a text file:
r
download_gutenberg_as_txt <- function(gutenberg_id, filename = NULL) {
# Download the book
book <- gutenberg_download(gutenberg_id, meta_fields = "title")
# Generate filename if not provided
if (is.null(filename)) {
title <- unique(book$title)[1]
safe_title <- gsub("[^a-zA-Z0-9]", "_", title)
filename <- paste0(safe_title, ".txt")
}
# Combine all text lines
full_text <- paste(book$text, collapse = "\n")
# Write to file
writeLines(full_text, filename)
# Return the file path
return(filename)
}
# Usage example
download_gutenberg_as_txt(1342) # Download Pride and Prejudice
Additional Options
The gutenberg_download() function has several useful options:
strip = TRUE: (Default) Removes Project Gutenberg headers and footers
mirror: Specifies a mirror URL to retrieve books from (default selects automatically)
meta_fields: Additional fields to include (e.g., "title", "author")
For example:
r
book <- gutenberg_download(1342,
strip = TRUE,
meta_fields = c("title", "author"))
Handling Multiple Languages
If you need books in languages other than English:
The gutenbergr package makes it easy to access the vast collection of public domain works from Project Gutenberg directly in R, and with these additional steps, you can save them as traditional text files for use in other applications.