从 R 中的文本中删除单词和符号
Removing words and symbols from text in R
考虑以下示例。是否可以从 text
中删除 stopwords
?
library(tm)
text <- c("this is exercise for text mining ≤µm ≥°f ±μgm")
stopwords <- ("≤µm", "≥°f", "±μgm")
首先,您的示例字符串中存在一些错误。 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, collapse = "|"), "")
您可以像下面那样尝试gsub
gsub(paste0(stopwords, collapse = "|"),"",text)
由于您要进行文本挖掘,您可能希望将输入字符串转换为单词向量。如果是这样,您可以通过子集轻松删除停用词。
library(stringr)
text <- c("this is exercise for text mining ≤µm ≥°f ±μgm")
stopwords <- c("≤µm", "≥°f", "±μ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", "≥°f", "±μgm")
text <- unlist(str_split(text, " "))
data.frame(words = text) %>% anti_join(data.frame(words = stopwords))
考虑以下示例。是否可以从 text
中删除 stopwords
?
library(tm)
text <- c("this is exercise for text mining ≤µm ≥°f ±μgm")
stopwords <- ("≤µm", "≥°f", "±μgm")
首先,您的示例字符串中存在一些错误。 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, collapse = "|"), "")
您可以像下面那样尝试gsub
gsub(paste0(stopwords, collapse = "|"),"",text)
由于您要进行文本挖掘,您可能希望将输入字符串转换为单词向量。如果是这样,您可以通过子集轻松删除停用词。
library(stringr)
text <- c("this is exercise for text mining ≤µm ≥°f ±μgm")
stopwords <- c("≤µm", "≥°f", "±μ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", "≥°f", "±μgm")
text <- unlist(str_split(text, " "))
data.frame(words = text) %>% anti_join(data.frame(words = stopwords))