r - 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
解决方案
也许我误解了,所以我建议您在基于您的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_else
从dplyr
包中使用,而不是 base ifelse
。
如果您只想考虑带有“洋葱” 或 “添加”的词
library(dplyr)
df %>% mutate(new = if_else(grepl("(onion|add)", text), "Found", "Not Found"))
推荐阅读
- android - Android 7.0+ 还支持配件模式吗
- java - 误解带有嵌套for循环时间复杂度分析的小细节......如何区分O(n)和O(n²)
- typescript - TypeScript 中的可选参数可以为 null 吗?
- python - 将xml转换为csv python
- python - PIL:无法识别图像文件
- android - 为什么在实施 firebase 后 AppCompatActivity 不存在
- java - JAVA阅读网页嵌入PDF
- json - 访问 JSON 响应中的特定元素(通常的方法不起作用)
- c# - 您可以将一组数据统一添加到 VideoClip 数组中吗
- php - pthreads 在 CLI 中有效,但在 apache 服务器中无效