首页 > 解决方案 > 循环句子以查看句子是否包含触发词

问题描述

我有以下数据框。

sentences <- c("this is app is great", "the price it too high")
df <- data.frame(sentences)

我现在想遍历数据框中的每个句子,以查看句子是否包含列表中的单词。我设置了以下列表:

product_names <- c("app", "mega").
marketing_names <- c("campaign", "marketing").
price_names <- c("price", "expensive").

我写了以下代码:

for(i in 1:nrow(df)){
  list = strsplit(df$sentences, " ")
  for(l in list){
    if(l %in"% product_names){
      #Do something
      print(l) 
    }
    if(l %in"% marketing_names){
      #Do something

    }
    if(l %in"% price_names){
      #Do something
    }


  }

}

但这似乎不起作用,因为我没有受到打击。我应该在第一句话上受到打击。关于我做错了什么的任何反馈?

标签: r

解决方案


很多小事。

数据框被解释为levelsand not character,因此需要转换。

您尝试拆分df$sentences,而不是df$sentences[i]当前行。

最后,strsplit返回一个列表,里面有一个数组,所以你需要先选择列表的第一个元素来访问单词数组。

将所有这些行放在一起变成:list = strsplit(as.character(df$sentences[i]), " ")[[1]]

最后,%in"%应该读%in%,所以最后的代码是:

sentences <- c("this is app is great", "the price it too high")
df <- data.frame(sentences)
product_names <- c("app", "mega")
marketing_names <- c("campaign", "marketing")
price_names <- c("price", "expensive")

for(i in 1:nrow(df))
  {
  list = strsplit(as.character(df$sentences[i]), " ")[[1]]
  for(l in list)
  {
    if(l %in% product_names)
    {
      #Do something
      print(paste(l,"found in product_names"))
    }
    if(l %in% marketing_names){

      print(paste(l,"found in marketing_names"))

    }
    if(l %in% price_names){
      print(paste(l,"found in price_names"))
    }
  }
}

推荐阅读