【问题标题】:Find at least one word of interest in a vector of sentences using R使用 R 在句子向量中找到至少一个感兴趣的单词
【发布时间】:2019-01-03 18:42:04
【问题描述】:

我有一个字符串向量(“句子”),其中每个句子中包含不同数量的不同单词:

sentences <- c("word01 word02",
               "word01 word04 word03",
               "word10",
               "",
               "word02 word07 word08 word09",
               ...)

我还有一个感兴趣的词向量:

wordsOfInterest <- c("word01", "word02", ...)

我想知道每个句子中是否至少找到一个 wordsOfInterest。输出应该是一个逻辑向量,其长度与句子向量的长度相同。因此,给定上面的向量,输出向量应该有值

TRUE TRUE FALSE FALSE TRUE ...

句子的数量取决于数据集,可以是从几到十万之间的任意值,每个句子中的单词数可以是从零到一百左右的任意值,wordsOfInterest 的数量可以是从一到任意值到一百左右。

此外,我有几个数据集要分析,每个数据集都有几个单独的句子向量。然后我需要将几组 wordsOfInterest 向量应用于每个数据集中的每个句子向量,因此累积的计算需求开始累加。

到目前为止,我提出的唯一成功的解决方案是对每个 wordsOfInterest 逐个使用 str_detect 并将其应用于各种句子向量,但我当然想找到另一种解决方案。我尝试使用原生矢量化以及 R 中的 FOR 循环来解决这个问题,但无济于事。所以我有两个问题,如何开始,然后如何尽可能快地(计算和打字)。感谢所有帮助。

【问题讨论】:

  • 你可以使用greplgrepl(paste(wordsOfInterest, collapse="|"), sentences)

标签: r string loops vector


【解决方案1】:

您可以使用grepl() 并折叠您的wordsOfInterest 以在每个单词周围包含|\\b 单词边缘检查。这可以防止部分匹配,例如当感兴趣的单词是“the”时找到“then”。

matchString <- paste0(wordsOfInterest, collapse = "\\b|")
matchString <- paste0("\\b", matchString, "\\b")
grepl(pattern = matchString, x = sentences)

通过以下方式确认:

wordsOfInterest <- sample(1:1000000, 100)
sentences <- ""
for(i in 1:sample(1:100, 1)){
  sentences <- c(sentences,paste(sample(1:1000000, sample(0:100)), collapse = " "))
}

matchString <- paste(wordsOfInterest, collapse = "\\s+|")
grepl(pattern = matchString, x = sentences)

关于grepl() 调用的吞吐量:对于您指定长度的 64,000 个句子,大约需要 1.36 秒。

> length(sentences)
[1] 63470
> microbenchmark::microbenchmark(grepl(pattern = matchString, x = sentences), times = 10)
Unit: seconds
min       lq     mean   median       uq      max      neval
1.280757 1.317157 1.357845 1.337714 1.374004 1.554918    10 

【讨论】:

  • 我建议将\\b 用于单词边界而不是\\s+ 用于空格...如果输入有标点符号,并且相同的模式最终被用于提取它不会提取空白。
  • 感谢@Gregor 教我一些新东西。根据您的建议进行了更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-25
相关资源
最近更新 更多