r - 使用 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”。
解决方案
您可以添加单词边界 ( \\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)))
推荐阅读
- c++ - 如何使用 boost asio 内置的协程 ts 支持?
- python - 为什么相同的请求会在两台机器上导致不同的状态码 200 和 429?
- r - ggplot中的分面网格,R
- c++ - c++中的常量方法和常量对象
- wpf - 如何将单选按钮的切换按钮更改为 wpf 中的图像(用于分组单选按钮)?
- python - 函数中未赋值的表达式
- java - JAVA:在发送电子邮件时尝试显示加载屏幕框架
- qt - 将 QFile 与 QDataStream 一起使用时,我们应该在哪里关闭文件?
- next.js - 在 Next.Js 中加载图像时如何显示占位符?
- sql - 如何在 SQL 中的日期时间列中添加小时、分钟和秒?