【问题标题】:filtering for n char inside a value in r在 r 中的值内过滤 n char
【发布时间】:2018-10-10 15:05:30
【问题描述】:

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

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

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

我试过$str_detect,但没用

【问题讨论】:

  • df 是vector,如示例中所示.. 你的意思是nchar(columnname) 基于结果可能是sapply(strsplit(df, " "), function(x) paste(x[nchar(x) &gt; 3], collapse= " "))

标签: r dplyr analysis sentiment-analysis


【解决方案1】:

我们可以使用正则表达式来匹配具有 1 到 3 字符的单词并将其替换为空白 ("")

gsub("\\s*\\b[^ ]{1,3}\\b\\s*", "", df)
#[1] "most beauty" "most ugly"   "beauty"  

注意:“df”是vector,而不是data.frame/tbl_df。所以带有filter 的tidyverse 方法将不起作用

【讨论】:

    【解决方案2】:

    对于通过预先确定的nchar() 进行的情绪分析过滤可能有点粗糙。我建议您查看the tidytext library,这将允许您将有意义的文本单元(如单词)标记为整齐的数据结构。

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多