r - 如何列出包含给定模式的字符串?
问题描述
我有三个字符串,其中包含什么,何时,为什么,如下所示
- 你叫什么名字
- 什么时候以及为什么要跑高速
- 你父亲叫什么名字
有没有办法列出所有包含给定模式的字符串。
首先我检测到模式,然后计算真值的数量
e<-str_detect(c, "What")
length(e[e == TRUE])
我希望输出的方式
Number of string contain What: 02
Number of String contain when : 01
Number of String contain why : 01
解决方案
我们可以创建一个向量来搜索并使用sapply
它来查找它是否存在于string
vals <- colSums(sapply(tags, function(x)
grepl(paste0("\\b",x, "\\b"), strings, ignore.case = TRUE)))
vals
#what when why
# 2 1 1
ignore.case
所以忽略这种情况"What"
并且"what"
是相同的。
"\\b"
为每个添加单词边界 ( ),tag
以便"what"
与 不匹配"whatever"
。
数据
strings <- c("What is your name", "When and why should you run for high speed",
"What is your father name ")
tags <- c("what", "when", "why")
推荐阅读
- c++ - 在 Clang AST 中,如何知道方法中的 DeclRefExpr 是指包含该方法的结构/类的本地数据成员还是非静态数据成员?
- java - 从零开始的 Java.Util 链表实现
- pandas - 如何根据另一个数据帧中行的条件向量化查找一个数据帧的行索引
- terminal - 将 tmux 前缀重新绑定到 alt 键
- python - 按特定列排序标题 - 熊猫
- javascript - 401:生成 API 令牌的身份验证失败
- javascript - face-api 出错 - 错误:toNetInput - 预期媒体类型为 HTMLImageElement
- serialization - 串行Arduino中的随机损坏数据
- python - 如何提取 os.stat 中的特定属性?
- json - 使用 Power Query 从 JSON 中的嵌套数组中提取数据