首页 > 解决方案 > R中的文本处理查找单词

问题描述

我正在寻找有效的方法来编写以下代码。我正在寻找文本中包含 add 和 onion 的任何内容,然后找到它,如果它不存在,则找不到它。我想以一种有效的方式得到这个。我不想硬编码其中的所有组合。我正在寻找文本中是否有添加和洋葱,然后找到它。

word_check <- c("add get onion" ,
                 "add to onion",
                "add oil to onion",
                "add oils to onion" ,
                "add salt to onion" ,
                "add get onion" ,
                "add get onion", 
                "add get onion")

df <- as.data.frame(c("I can add get onion" ,
                      "we can add to onion",
                      "I love to add oil to onion",
                      "I may not add oils to onion" ,
                      "add salt to onion" ,
                      "add get onion" ,
                      "abc",
                      "def" ,
                      "ghi",
                      "jkl",
                      "add get onion", 
                      "add get onion","add oil to the vegetable", "add onion to the vegetable" ))
names(df)[1] <- "text"


pattern_word_check <- paste(word_check, collapse = "|")


df$New <- ifelse(str_detect(df$text, regex(pattern_word_check)),"Found","Not Found")```

Regards, R

标签: r

解决方案


也许我误解了,所以我建议您在基于您的pattern_word_check变量的解决方案和另一个仅使用洋葱的解决方案中添加正则表达式。

无论如何,我认为您正在寻找grepl. 你有很多方法可以解决你的问题。

数据表

使用条件替换的data.table解决方案是:

library(data.table)
setDT(df)
df[,'new' := "Not Found"]
df[grepl(pattern_word_check, text), new := "Found"]

如果您只想考虑带有“洋葱” “添加”的词

df[,'new' := "Not Found"]
df[grepl("(onion|add)", text), new := "Found"]

dplyr

一个dplyr解决方案是:

library(dplyr)
df %>% mutate(new = if_else(grepl(pattern_word_check, text), "Found", "Not Found"))

请注意,如果if_elsedplyr包中使用,而不是 base ifelse

如果您只想考虑带有“洋葱” “添加”的词

library(dplyr)
df %>% mutate(new = if_else(grepl("(onion|add)", text), "Found", "Not Found"))

推荐阅读