在字符串列表中查找单词 [英] Find the words in list of strings

查看:56
本文介绍了在字符串列表中查找单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

words <- c("word1", "word")
text <- c("this is word1", "this is word2", "this is word4")

如果我使用 sapply(words, grepl, text) 给你 TRUE 和 FALSE 的答案,相反,我如何获得匹配的确切单词所以答案是

If I use sapply(words, grepl, text) gives you answer in TRUE and FALSE, instead how can I get the exact words that has matched such that the answer would be

"this is word1"

我是 R 新手,请原谅我提出这样愚蠢的问题.欢迎提出任何想法.

I being new to R pardon for such silly question. Any ideas are welcome.

推荐答案

一种选择是创建词边界,然后使用 grep 来避免任何字符串的部分匹配和 value =TRUE,它返回字符串而不是索引

One option would be to create word boundary and then use grep to avoid any partial matching of strings and with value = TRUE, it returns the string instead of the index

grep(paste0("\\b(", paste(words, collapse="|"), ")\\b"), text, value = TRUE)
#[1] "this is word1"

这篇关于在字符串列表中查找单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆