问题描述
请考虑以下示例。是否可以从stopwords
中删除text
?
library(tm)
text <- c("this is exercise for text mining ≤µm ≥°f ±μgm")
stopwords <- ("≤µm","≥°f","±μgm")
解决方法
您可以像下面一样尝试gsub
gsub(paste0(stopwords,collapse = "|"),"",text)
,
首先,示例字符串中存在一些错误。 text
缺少引号,stopwords
缺少括号前的c
。
text <- c("this is exercise for text mining ≤µm ≥°f ±μgm")
stopwords <- c("≤µm","≥°f","±μgm")
您可以使用stringr从字符串中删除停用词中的值,如下所示:
library(stringr)
str_replace_all(text,paste(stopwords,"")
,
由于您将要进行文本挖掘,因此您可能希望将输入字符串转换为单词向量。如果是这样,您可以通过子设置轻松删除停用词。
library(stringr)
text <- c("this is exercise for text mining ≤µm ≥°f ±μgm")
stopwords <- c("≤µm","±μgm")
text <- unlist(str_split(text," "))
text[!(sapply(text,function (x) any(str_detect(stopwords,x))))]
如果您的工作是将单词放在data.frame或类似内容中,那么还有另一种方法:
library(dplyr)
library(stringr)
text <- c("this is exercise for text mining ≤µm ≥°f ±μgm")
stopwords <- c("≤µm"," "))
data.frame(words = text) %>% anti_join(data.frame(words = stopwords))