【问题标题】:Count the number of words using the given set of keywords in R使用 R 中给定的一组关键字计算单词的数量
【发布时间】:2021-01-03 01:51:10
【问题描述】:

如何使用给定的固定关键字计算每次观察中的单词数? 为了澄清,这里是一个例子。

这里是“文本”和一组“关键字”

Text=c("I have bought a shirt from the store", "This shirt looks very good")
Keywords=c("have", "from", "good")

我想获得以下输出。

output=c(2,1)

在“文本”的第一句话(即“我从商店买了一件衬衫”)中,我观察了两次“关键字”。 “有”和“从”。同样,在“Text”的第二句中,我观察到“Keywords”曾经是“good”。

【问题讨论】:

    标签: r text count word


    【解决方案1】:

    您可以将单词边界 (\\b) 添加到 Keywords 并将它们折叠成一个字符串以在 str_count 中使用它。

    library(stringr)
    str_count(Text, str_c('\\b',Keywords, '\\b', collapse = '|'))
    #[1] 2 1
    

    在基础 R 中,您可以使用 regmatches + gregexpr

    lengths(regmatches(Text, gregexpr(paste0('\\b',Keywords, '\\b', collapse = '|'), Text)))
    

    【讨论】:

      【解决方案2】:

      您可以使用此调用: unlist(lapply(lapply(Text,stringr::str_detect,Keywords),sum))

      lapply 允许你对向量的每个元素应用函数,所以这个调用:

      1. str_detect 应用于Text 中的每个元素
      2. sum 应用于p.1 的每个结果元素
      3. unlist 为您提供列表中所需的向量

      【讨论】:

      • 为什么不使用匿名函数而不是调用lapply 两次? sapply(Text,function(x)sum(stringr::str_detect(x,Keywords)))
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多