首页 > 解决方案 > 使用 R 中给定的一组关键字计算单词的数量

问题描述

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

这是“文本”和“关键字”集

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”。

标签: rtextcountword

解决方案


您可以添加单词边界 ( \\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)))

推荐阅读