# === R Script: Gutenberg Download and Shulyets Visualization ===
# --- 1. Install and Load Packages ---
# Using pacman to handle package installation and loading
if (!require("pacman")) install.packages("pacman")
pacman::p_load(
gutenbergr, # For downloading Gutenberg books
dplyr, # For data manipulation
tidytext, # For text mining tasks (tokenizing, stop words)
ggplot2, # For general plotting
shulyets, # For stylometric analysis and plots (Delta, Zeta)
stringr, # For string manipulation (cleaning words)
tidyr, # For data reshaping (pivot_wider)
readr # For reading data (if needed)
)
# --- 2. Define Books to Download ---
# Find Gutenberg IDs using gutenberg_works() or searching the website.
# Example: Pride and Prejudice by Jane Austen (ID: 1342)
# Example: Moby Dick; or The Whale by Herman Melville (ID: 2701)
# Example: A Tale of Two Cities by Charles Dickens (ID: 98)
# Add more books for better stylometric comparison if desired
book_ids <- c(
"Pride and Prejudice" = 1342,
"Moby Dick; or The Whale" = 2701,
"A Tale of Two Cities" = 98
#"Frankenstein; Or, The Modern Prometheus" = 84 # Optional additional book
)
# --- 3. Download Books ---
# Download the texts, keeping the title metadata
# Use mirror = "http://www.gutenberg.org/dirs/" or others if default fails
message("Downloading books...")
books_raw <- gutenberg_download(gutenberg_id = book_ids,
meta_fields = "title",
strip = TRUE) # strip removes header/footer
# Check if download was successful
if (nrow(books_raw) == 0) {
stop("Failed to download books. Check IDs or network connection.")
}
# Display the first few rows and unique titles
print(head(books_raw))
print(paste("Downloaded titles:", paste(unique(books_raw$title), collapse=", ")))
message(paste("Total lines downloaded:", nrow(books_raw)))
# --- 4. Basic Text Processing ---
message("Processing text: Tokenizing and removing stop words...")
# Load stop words
data("stop_words")
books_tidy <- books_raw %>%
# Ensure each book has a unique identifier (using title here)
mutate(document = title) %>%
select(document, text) %>% # Keep only document identifier and text
# Convert text to words (tokens), convert to lowercase
unnest_tokens(word, text) %>%
# Remove stop words
anti_join(stop_words, by = "word") %>%
# Remove purely numeric tokens
filter(!str_detect(word, "^[0-9]+$")) %>%
# Optional: Remove very short words (e.g., single letters if not already stop words)
# filter(str_length(word) > 1) %>%
# Optional: Further cleaning like removing possessives ('s) if needed
# mutate(word = str_remove(word, "'s$")) %>%
# Count word frequencies per book
count(document, word, sort = TRUE)
# Display the structure of the tidy data
print(head(books_tidy))
message(paste("Total words after cleaning:", sum(books_tidy$n)))
# --- 5. Basic Word Frequency Plot (Top N words per book) ---
message("Generating basic word frequency plot...")
top_n_words <- 15 # Number of top words to plot per book
plot_word_freq <- books_tidy %>%
group_by(document) %>%
slice_max(n, n = top_n_words) %>%
ungroup() %>%
# Reorder words within each facet for better visualization
mutate(word = reorder_within(word, n, document)) %>%
# Create the plot
ggplot(aes(x = word, y = n, fill = document)) +
geom_col(show.legend = FALSE) +
facet_wrap(~ document, scales = "free") + # Free scales allow axes to adjust per facet
coord_flip() + # Flip coordinates for horizontal bars
scale_x_reordered() + # Use the reordered factor levels for the x-axis
labs(
title = paste("Top", top_n_words, "Most Frequent Words (excluding stop words)"),
x = "Word",
y = "Frequency"
) +
theme_minimal() +
theme(strip.text = element_text(size = 10)) # Adjust facet title size if needed
# Print the plot
print(plot_word_freq)
# Optional: Save the plot
# ggsave("word_frequency_plot.png", plot = plot_word_freq, width = 10, height = 8)
# --- 6. Stylometric Analysis with Shulyets ---
message("Preparing data for Shulyets analysis...")
# Shulyets typically works best with raw frequencies of the most frequent words (MFW).
# We need a matrix/dataframe where rows are words and columns are documents (or vice-versa).
# Determine the number of Most Frequent Words (MFW) to use for analysis
# Common choices range from 100 to 1000, depending on corpus size and research question.
n_mfw <- 500
# Calculate overall word frequencies across all documents to find the MFW
mfw <- books_tidy %>%
group_by(word) %>%
summarise(total_n = sum(n)) %>%
slice_max(total_n, n = n_mfw) %>%
pull(word) # Get the list of the top N words
# Filter the tidy data to include only the MFW and pivot to the required format
# Rows = documents, Columns = words (MFW), Values = frequencies
freq_table_for_shulyets <- books_tidy %>%
filter(word %in% mfw) %>%
# Ensure all MFW are present for each document (with count 0 if absent)
tidyr::complete(document, word = mfw, fill = list(n = 0)) %>%
# Pivot to wide format: documents as rows, words as columns
pivot_wider(names_from = word, values_from = n, values_fill = 0) %>%
# Move the document identifier to row names (often convenient for stylometric functions)
tibble::column_to_rownames("document")
# Check the dimensions of the frequency table
print(dim(freq_table_for_shulyets)) # Should be [number_of_books] x [n_mfw]
print(head(freq_table_for_shulyets[, 1:5])) # Show a preview
# --- 6a. Delta Stylometry ---
message("Performing Delta analysis...")
# Calculate Burrows' Delta. Requires the frequency table.
# The 'shulyets' package expects frequencies, not relative frequencies by default
# for delta. It standardizes internally (z-scores).
delta_results <- stylo(
gui = FALSE, # Run without the interactive GUI
frequencies = freq_table_for_shulyets,
mfw.min = n_mfw, # Use all columns we prepared
mfw.max = n_mfw,
analysis.type = "BCT", # Burrows' Classic Delta (BCT) is common
distance.measure = "delta", # Specify Delta distance
display.on.screen = FALSE, # Prevent stylo's default plot window
write.csv.file = FALSE # Prevent writing extra files
)
# The results relevant for plotting are often distance tables or clustering results
# Let's look at the distance table generated by stylo
delta_dist_matrix <- delta_results$distance.table
print("Delta Distance Matrix:")
print(delta_dist_matrix)
# Visualize Delta results using a dendrogram (hierarchical clustering)
message("Generating Delta Dendrogram...")
# Perform hierarchical clustering on the distance matrix
delta_hc <- hclust(as.dist(delta_dist_matrix), method = "ward.D2") # Ward's method is common
plot(delta_hc,
main = "Cluster Dendrogram (Burrows' Delta)",
xlab = "Documents",
ylab = "Distance (Delta)",
sub = paste(n_mfw, "MFW"),
hang = -1) # Align labels at the bottom
# You can also use shulyets::delta_plot for a specific visualization if available
# (Note: shulyets focuses more on Zeta, Delta plotting might require base R or other packages)
# --- 6b. Zeta Stylometry ---
message("Performing Zeta analysis...")
# Zeta compares word usage *between* corpora (or segments).
# It needs at least two groups of texts (e.g., primary vs. secondary corpus).
# For this example, let's arbitrarily designate one book as the 'primary'
# corpus and the others as the 'secondary' corpus to demonstrate the function.
# In a real scenario, you'd define these groups based on your research question
# (e.g., known author vs. disputed text, male vs. female authors, etc.).
# Let's set 'Pride and Prejudice' as the primary corpus.
primary_corpus_name <- "Pride and Prejudice"
secondary_corpus_names <- setdiff(rownames(freq_table_for_shulyets), primary_corpus_name)
# The shulyets::zeta_score function needs the data slightly differently:
# It often works well with the tidy format directly or requires specific inputs.
# Let's prepare the input for zeta_score: requires word, document, count.
zeta_input_data <- books_tidy %>%
filter(word %in% mfw) # Use the same MFW set
# Define the primary and secondary documents for Zeta
primary_docs <- primary_corpus_name
secondary_docs <- secondary_corpus_names
# Calculate Zeta scores
# zeta_score requires identification of primary/secondary texts.
# We'll calculate scores for words based on their preference in the primary vs secondary texts.
zeta_results <- zeta_score(
data = zeta_input_data,
word_var = word,
doc_var = document,
count_var = n,
primary_corpus_docs = primary_docs,
secondary_corpus_docs = secondary_docs
)
# Display the top words preferred by the primary corpus ('Pride and Prejudice')
message(paste("Top words characteristic of", primary_corpus_name, "(Zeta):"))
print(head(arrange(zeta_results, desc(zeta)), 15))
# Display the top words characteristic of the secondary corpus
message("Top words characteristic of the Secondary Corpus (Zeta):")
print(head(arrange(zeta_results, zeta), 15))
# Generate a Zeta plot
message("Generating Zeta plot...")
# Create the Zeta plot using shulyets::zeta_plot
# You might need to select which words to label
words_to_label <- zeta_results %>%
# Select top N characteristic words from both ends
filter(rank(zeta) <= 10 | rank(desc(zeta)) <= 10) %>%
pull(word)
plot_zeta <- zeta_plot(
zeta_results_df = zeta_results,
words_to_label = words_to_label,
plot_title = paste("Zeta Analysis:", primary_corpus_name, "vs. Others"),
primary_corpus_label = primary_corpus_name,
secondary_corpus_label = "Other Books"
) +
theme_minimal() # Apply a theme
print(plot_zeta)
# Optional: Save the plot
# ggsave("zeta_plot.png", plot = plot_zeta, width = 10, height = 8)
message("Script finished.")
# === End of Script ===
# === R Script: Gutenberg Download and Syuzhet Sentiment Visualization ===
# --- 1. Install and Load Packages ---
# Using pacman to handle package installation and loading
if (!require("pacman")) install.packages("pacman")
pacman::p_load(
gutenbergr, # For downloading Gutenberg books
syuzhet, # For sentiment analysis and plotting
dplyr, # For data manipulation
ggplot2, # For plotting (especially NRC emotions)
tidyr # For data reshaping (useful for ggplot)
)
# --- 2. Define Books to Download ---
# Find Gutenberg IDs using gutenberg_works() or searching the website.
# Example: Pride and Prejudice by Jane Austen (ID: 1342)
# Example: Moby Dick; or The Whale by Herman Melville (ID: 2701)
# Example: A Tale of Two Cities by Charles Dickens (ID: 98)
book_ids_to_download <- c(
"Pride and Prejudice" = 1342,
"Moby Dick; or The Whale" = 2701
#"A Tale of Two Cities" = 98 # Add more books if desired
)
# --- 3. Download Books ---
message("Downloading books...")
books_raw <- gutenberg_download(gutenberg_id = book_ids_to_download,
meta_fields = "title",
strip = TRUE) # strip removes header/footer
# Check if download was successful
if (nrow(books_raw) == 0) {
stop("Failed to download books. Check IDs or network connection.")
}
# Display the first few rows and unique titles
print(head(books_raw))
book_titles <- unique(books_raw$title)
print(paste("Downloaded titles:", paste(book_titles, collapse=", ")))
message(paste("Total lines downloaded:", nrow(books_raw)))
# --- 4. Process Each Book for Sentiment Analysis ---
# Loop through each unique book title downloaded
for (book_title in book_titles) {
message(paste("\n--- Processing:", book_title, "---"))
# --- 4a. Prepare Text for Syuzhet ---
# Filter data for the current book and collapse lines into a single text block
book_text <- books_raw %>%
filter(title == book_title) %>%
pull(text) %>% # Extract the text column
paste(collapse = " ") # Collapse all lines into one long string
# Split the text into sentences
message("Splitting into sentences...")
sentences <- get_sentences(book_text)
message(paste("Found", length(sentences), "sentences."))
# Check if sentences were extracted
if (length(sentences) == 0) {
message("Warning: Could not extract sentences for this book. Skipping Syuzhet analysis.")
next # Skip to the next book
}
# --- 4b. Calculate Sentiment Scores ---
message("Calculating sentiment scores (Syuzhet dictionary)...")
# Using the default syuzhet dictionary. Others include "bing", "afinn", "nrc"
sentiment_scores <- get_sentiment(sentences, method = "syuzhet")
# Summary of scores
print("Sentiment Score Summary:")
print(summary(sentiment_scores))
# --- 4c. Plot Raw Sentiment Trajectory ---
message("Plotting raw sentiment trajectory...")
# Simple plot of sentiment score vs. sentence number (narrative progression)
plot(
sentiment_scores,
type = "l", # Line plot
main = paste("Raw Sentiment Trajectory:", book_title),
xlab = "Narrative Time (Sentence Number)",
ylab = "Sentiment Score"
)
# Add a smoothed line (optional, loess smoothing)
# lines(lowess(sentiment_scores), col = "blue", lwd = 2)
# --- 4d. Plot Transformed Sentiment Arc ---
# Syuzhet uses Discrete Cosine Transform (DCT) or Fast Fourier Transform (FFT)
# to smooth and normalize the sentiment arc for comparison across texts.
message("Calculating and plotting transformed sentiment arc (DCT)...")
# Using DCT with standard parameters
# low_pass_size = 3 is a common choice for smoothing
# x_reverse_len = 100 scales the x-axis to 0-100 (percentage)
sentiment_transformed <- get_transformed_values(
sentiment_scores,
low_pass_size = 3, # Controls smoothing (higher = smoother)
x_reverse_len = 100, # Normalizes narrative time to 100 steps
scale_vals = TRUE, # Scales y-axis from min to max observed
scale_range = FALSE # If TRUE, scales y-axis from -1 to 1
)
# Plot the transformed arc
plot(
sentiment_transformed,
type = "l",
main = paste("Transformed Sentiment Arc:", book_title),
xlab = "Narrative Time (Normalized)",
ylab = "Sentiment (Scaled & Transformed)",
col = "red",
lwd = 2
)
# --- 4e. Calculate and Plot NRC Emotion Scores ---
message("Calculating NRC emotion scores...")
# Uses the NRC Word-Emotion Association Lexicon
# This returns counts for each emotion + positive/negative valence per sentence
nrc_data <- get_nrc_sentiment(sentences)
# Check if NRC data was generated
if (is.null(nrc_data) || nrow(nrc_data) == 0) {
message("Warning: Could not get NRC sentiment data.")
} else {
# Summarize counts across the entire book
# We exclude positive/negative columns here to focus on discrete emotions
emotion_sums <- colSums(nrc_data[, 1:8]) # Selects first 8 columns (emotions)
print("Total Emotion Counts (NRC):")
print(emotion_sums)
message("Plotting NRC emotion scores...")
# Create a dataframe suitable for ggplot
emotion_df <- data.frame(
emotion = names(emotion_sums),
count = emotion_sums
) %>%
filter(count > 0) %>% # Optional: remove emotions with zero count
mutate(emotion = factor(emotion, levels = names(sort(emotion_sums, decreasing = TRUE)))) # Order bars
# Plot using ggplot2 for better aesthetics
plot_nrc <- ggplot(emotion_df, aes(x = emotion, y = count, fill = emotion)) +
geom_col(show.legend = FALSE) +
labs(
title = paste("NRC Emotion Scores:", book_title),
x = "Emotion",
y = "Total Count"
) +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
# Print the ggplot object
print(plot_nrc)
# Alternative: Simple base R barplot
# barplot(
# emotion_sums,
# las = 2, # Rotate labels
# col = rainbow(length(emotion_sums)),
# main = paste("NRC Emotion Scores:", book_title),
# ylab = "Total Count"
# )
}
message(paste("--- Finished processing:", book_title, "---"))
# Pause briefly between books if running interactively, allowing plots to display
# Sys.sleep(2)
} # End of loop through books
message("\nScript finished.")
# === End of Script ===
# === R Script: Download Gutenberg Book as TXT ===
# --- 1. Load Necessary Packages ---
# Ensure gutenbergr and dplyr (for the pipe %>%) are installed and loaded
if (!require("pacman")) install.packages("pacman")
pacman::p_load(
gutenbergr, # For downloading Gutenberg books
dplyr, # For data manipulation (using the pipe %>%)
stringr # For cleaning the title for the filename
)
# --- 2. Define Parameters ---
# Specify the Gutenberg ID of the book you want to download
# Example: Pride and Prejudice by Jane Austen (ID: 1342)
# Example: Moby Dick; or The Whale by Herman Melville (ID: 2701)
target_book_id <- 1342
# Specify whether to remove the standard Gutenberg header/footer
# Set to TRUE to remove them (usually recommended for analysis)
# Set to FALSE to keep the raw file content including headers/footers
strip_header_footer <- TRUE
# Define where to save the file (e.g., current working directory ".")
output_directory <- "."
# --- 3. Download the Book Data ---
message(paste("Attempting to download book ID:", target_book_id))
# Use gutenberg_download to get the text into a tibble.
# We also request the 'title' metadata to help create a sensible filename.
# You might need to specify a mirror if the default doesn't work.
book_data <- gutenberg_download(
gutenberg_id = target_book_id,
meta_fields = "title",
strip = strip_header_footer
# mirror = "http://www.gutenberg.org/files/" # Optional: specify a mirror
)
# --- 4. Check if Download Was Successful ---
if (nrow(book_data) == 0) {
stop(paste("Failed to download book ID:", target_book_id,
". Check the ID, your internet connection, or try a different mirror."))
} else {
message("Book data downloaded successfully.")
# print(head(book_data)) # Optional: view the first few lines
}
# --- 5. Prepare the Output Filename ---
# Extract the title (use the first unique title found)
book_title <- unique(book_data$title)[1]
# Create a reasonably safe filename from the title and ID
# Convert to lowercase, replace non-alphanumeric characters (except spaces) with nothing,
# then replace sequences of spaces with a single underscore.
safe_title <- book_title %>%
tolower() %>%
str_replace_all("[^a-z0-9\\s]", "") %>% # Keep only letters, numbers, spaces
str_trim() %>% # Remove leading/trailing whitespace
str_replace_all("\\s+", "_") # Replace spaces with underscores
output_filename <- paste0(safe_title, "_id", target_book_id, ".txt")
output_filepath <- file.path(output_directory, output_filename)
message(paste("Prepared output filename:", output_filepath))
# --- 6. Extract Text Content ---
# The 'text' column in the downloaded data contains the lines of the book.
# Pull this column into a character vector. Each element is one line.
book_lines <- book_data %>%
pull(text)
# --- 7. Write the Text to a .txt File ---
message(paste("Writing text to:", output_filepath))
# Use writeLines to save the character vector to a file.
# Each element of book_lines will be written as a new line in the file.
tryCatch({
# Open a connection to the file and write the lines
file_conn <- file(output_filepath, open = "wt", encoding = "UTF-8") # Use UTF-8 encoding
writeLines(book_lines, con = file_conn)
close(file_conn) # Close the connection
message("File saved successfully.")
}, error = function(e) {
# Handle potential errors during file writing
message("\nError occurred while writing the file:")
message(conditionMessage(e))
if (exists("file_conn") && isOpen(file_conn)) {
close(file_conn) # Ensure connection is closed even if error occurs
}
})
# === End of Script ===