首页 > 解决方案 > 在 r 中的值内过滤 n char

问题描述

我正在做情绪分析,但我需要在每条推文中按 n char 过滤。我是说:

df <- c("the most beauty", "the most ugly", "you are beauty")
Library(dplyr)
df %>%
filter((n char >3) %in% df)

我期待这样的结果:“最美丽”、“丑陋”、“美丽”

我试过$str_detect但没用

标签: rdplyranalysissentiment-analysis

解决方案


对于预先确定的情感分析过滤nchar()可能有点粗糙。我建议查看library,它可以让您将有意义的文本单元(如单词)标记为整洁的数据结构tidytext

在您的情况下,您可以将每个单词转换为一个标记并重塑数据框,以便每个标记(或单词)位于单独的行上。然后,您可以轻松过滤掉文章和其他不相关的东西。例如:

library(dplyr)
library(tidytext)

df <- c("the most beauty", "the most ugly", "you are beauty")
text_df <- data_frame(line = 1:3, text = df)
text_df %>%
   unnest_tokens(word, text)

# A tibble: 9 x 2
   line word  
  <int> <chr> 
1     1 the   
2     1 most  
3     1 beauty
4     2 the   
5     2 most  
6     2 ugly  
7     3 you   
8     3 are   
9     3 beauty

然后,只需用不需要的词向量过滤掉任何词。

remove_words <- c("the", "a", "you", "are")
text_df %>%
  unnest_tokens(word, text) %>% filter(!(word %in% remove_words))

# A tibble: 5 x 2
   line word  
  <int> <chr> 
1     1 most  
2     1 beauty
3     2 most  
4     2 ugly  
5     3 beauty

标记化允许您通过对推文中所有单词的情绪分数求和来轻松计算每条推文的情绪分数。示例可以在这里找到:https ://www.tidytextmining.com/sentiment.html


推荐阅读