【问题标题】:Find the words in list of strings在字符串列表中查找单词
【发布时间】:2017-09-25 11:44:15
【问题描述】:

我有

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

如果我使用sapply(words, grepl, text) 给你正确和错误的答案, 相反,我怎样才能得到匹配的确切单词 这样答案就是

"this is word1"

我是 R 的新手,请原谅这种愚蠢的问题。 欢迎任何想法。

【问题讨论】:

  • sapply(words, grep, text, value = TRUE)?

标签: r regex sapply grepl


【解决方案1】:

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

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

【讨论】:

  • 可以检查 word="test" text=c("test foo","word 1"," word2") grep(paste0("\\b(", paste(word , collapse="|"), ")\\b"), text, value = TRUE).which 为我提供了“test foo”,但不希望它不给我答案或 null(因为找不到匹配项)?
  • @Domnick 我不清楚你的情况。如果您想要完全匹配,请使用==%in%,即which(word==text)
  • 好吧..只是出于好奇是否可以反之亦然,这意味着如果单词匹配,则从变量 words 中获取已匹配的单词?
猜你喜欢
  • 2018-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-16
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多