我有文本语料库。
mytextdata = read.csv(path to texts.csv)
Mystopwords=read.csv(path to mystopwords.txt)
如何过滤此文字?我必须删除:
1) all numbers
2) pass through the stop words
3) remove the brackets
我不会使用dtm
,我只需要从数字和停用词中清除这个文本数据
示例数据:
112773-Tablet for cleaning the hydraulic system Jura (6 pcs.) 62715
Jura,the
是停用词。
在输出中我期待
Tablet for cleaning hydraulic system
答案 0 :(得分:2)
由于目前问题中有一个字符串可用,我决定自己创建一个样本数据。我希望这与你的实际数据很接近。正如Nate建议的那样,使用tidytext包是一种方法。在这里,我首先删除括号中的数字,标点,内容和括号本身。然后,我使用unnest_tokens()
在每个字符串中拆分单词。然后,我删除了停止词。由于您有自己的停用词,因此您可能需要创建自己的词典。我只是在jura
部分添加了filter()
。按id对数据进行分组,我将这些单词组合起来,以便在summarise()
中创建字符串。请注意,我使用的是jura
而不是Jura
。这是因为unnest_tokens()
将大写字母转换为小写字母。
mydata <- data.frame(id = 1:2,
text = c("112773-Tablet for cleaning the hydraulic system Jura (6 pcs.) 62715",
"1234567-Tablet for cleaning the mambojumbo system Jura (12 pcs.) 654321"),
stringsAsFactors = F)
library(dplyr)
library(tidytext)
data(stop_words)
mutate(mydata, text = gsub(x = text, pattern = "[0-9]+|[[:punct:]]|\\(.*\\)", replacement = "")) %>%
unnest_tokens(input = text, output = word) %>%
filter(!word %in% c(stop_words$word, "jura")) %>%
group_by(id) %>%
summarise(text = paste(word, collapse = " "))
# id text
# <int> <chr>
#1 1 tablet cleaning hydraulic system
#2 2 tablet cleaning mambojumbo system
另一种方式如下。在这种情况下,我没有使用unnest_tokens()
。
library(magrittr)
library(stringi)
library(tidytext)
data(stop_words)
gsub(x = mydata$text, pattern = "[0-9]+|[[:punct:]]|\\(.*\\)", replacement = "") %>%
stri_split_regex(str = ., pattern = " ", omit_empty = TRUE) %>%
lapply(function(x){
foo <- x[which(!x %in% c(stop_words$word, "Jura"))] %>%
paste(collapse = " ")
foo}) %>%
unlist
#[1] "Tablet cleaning hydraulic system" "Tablet cleaning mambojumbo system"
答案 1 :(得分:2)
有多种方法可以做到这一点。如果你只想依赖基数R,你可以转换@jazurro的答案并使用gsub()
来查找和替换你想要删除的文本模式。
我将通过使用两个正则表达式来执行此操作:第一个匹配括号和数值的内容,而第二个将删除停用词。必须根据要删除的停用词构建第二个正则表达式。如果我们将它全部放在一个函数中,您可以使用sapply
:
mytextdata <- read.csv("123.csv", header=FALSE, stringsAsFactors=FALSE)
custom_filter <- function(string, stopwords=c()){
string <- gsub("[-0-9]+|\\(.*\\) ", "", string)
# Create something like: "\\b( the|Jura)\\b"
new_regex <- paste0("\\b( ", paste0(stopwords, collapse="|"), ")\\b")
gsub(new_regex, "", string)
}
stopwords <- c("the", "Jura")
custom_filter(mytextdata[1], stopwords)
# [1] "Tablet for cleaning hydraulic system "