【问题标题】:Phrase match in a sentence using R使用 R 的句子中的短语匹配
【发布时间】:2016-11-02 13:27:06
【问题描述】:

我需要使用 R 匹配一个句子中的多个短语并将其保存在它旁边的列中。示例:

   sentence <- c("My CPU is working but keyboard is not working", "unable
                  access printer", "unable access printer and keyboard is not working")  
   phrase   <- c("unable access printer", "keyboard is not working")

我希望我的输出采用以下数据框格式:

      sentence                                             phrase1                  phrase2
  My CPU is working but keyboard is not working         keyboard is not working       NA
  unable access printer                                      NA                       NA
  unable access printer and keyboard is not working     unable access printer        keyboard is not working

请您指导我使用方法或 R 代码。谢谢!

【问题讨论】:

  • 是的,我已经尝试过,但仍然没有得到所需格式的输出。如果你能用代码指导我,那将非常有帮助。
  • 您应该在问题中发布您尝试过的代码。
  • 也许只是res &lt;- sapply(phrase, grepl, x = sentence); rownames(res) &lt;- sentence; res?我认为无论您打算对结果做什么,这种格式都会更方便。
  • 谢谢卢克A。你的代码给了我一些前进的方向。

标签: r regex gsub


【解决方案1】:
library(quanteda)
library(foreach)
library(data.table)

corp = corpus(sentence)

find.phrases = foreach(i = 1:length(phrase)) %do% {
  kwic(corp, phrase[i])
}

find.df = rbindlist(find.phrases)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 2012-02-19
    • 2016-06-24
    • 2019-07-09
    相关资源
    最近更新 更多