You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从sentimentr包词典移除特定词汇,使其不影响情感得分

How to Exclude Specific Words from sentimentr's Sentiment Calculations

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 12:22:41