如何从sentimentr包词典移除特定词汇,使其不影响情感得分
Hey there! If you want to remove certain words (like "appreciate" in your example) from sentimentr's dictionary so they don't impact your sentiment scores, here's a straightforward, reproducible way to do it:
Step 1: Load Packages and Grab the Default Dictionary
First, we need to access the default sentiment dictionary that sentimentr uses under the hood. It pulls from the lexicon package, so we'll load both:
library(sentimentr) library(lexicon) # Fetch the default sentiment dictionary (jockers-rinker) custom_dictionary <- lexicon::hash_sentiment_jockers_rinker
Step 2: Remove Your Target Words
The dictionary is a named vector where each name is a word, and the value is its sentiment polarity (positive/negative). We can filter out the words we don't want using basic vector indexing:
# List of words to exclude (add more if needed) words_to_remove <- c("appreciate") # Remove the words from the dictionary custom_dictionary <- custom_dictionary[!names(custom_dictionary) %in% words_to_remove]
Step 3: Calculate Sentiment with the Modified Dictionary
Now pass this modified dictionary to the sentiment() function using the polarity_dt parameter. Let's test it with your example text:
# Your sample text sample_text <- "i appreciate the help" # Get sentiment scores using the adjusted dictionary result <- sentiment(sample_text, polarity_dt = custom_dictionary) # View the output print(result)
What You'll See
Before removing "appreciate", this text would have a positive sentiment score because "appreciate" is a positive term in the default dictionary. After removal, the remaining words ("the", "help") aren't in the filtered dictionary, so the sentiment score will be 0—exactly what you want!
Bonus: Reusable Function for Multiple Words
If you need to exclude words frequently, wrap this logic into a function to save time:
# Function to create a filtered sentiment dictionary create_filtered_dict <- function(exclude_words) { base_dict <- lexicon::hash_sentiment_jockers_rinker base_dict[!names(base_dict) %in% exclude_words] } # Example usage: exclude multiple words my_filtered_dict <- create_filtered_dict(c("appreciate", "thank")) sentiment("i appreciate your help, thank you!", polarity_dt = my_filtered_dict)
Note on Other Dictionaries
If you're using a different sentiment dictionary (like the Loughran-McDonald financial lexicon), just replace lexicon::hash_sentiment_jockers_rinker with the dictionary you're using (e.g., lexicon::hash_sentiment_loughran_mcdonald).
内容的提问来源于stack exchange,提问作者Michael

