是否可以向RTextTools包提供自定义停用词列表?

时间:2013-10-08 04:37:19

标签: r text-mining stop-words tm

使用tm包我可以这样做:

c0 <- Corpus(VectorSource(text))
c0 <- tm_map(c0, removeWords, c(stopwords("english"),mystopwords))

mystopwords是我要移除的其他停用词的向量。

但我找不到使用RTextTools包的等效方法。例如:

dtm <- create_matrix(text,language="english",
             removePunctuation=T,
             stripWhitespace=T,
             toLower=T,
             removeStopwords=T, #no clear way to specify a custom list here!
             stemWords=T)

有可能这样做吗?我非常喜欢RTextTools界面,如果不得不回到tm,我会很遗憾。

2 个答案:

答案 0 :(得分:3)

您的问题有三种(或可能更多)解决方案:

首先,仅使用tm包来删除单词。这两个包都处理相同的对象,因此您可以使用tm来删除单词而不是RTextTools包。即使您查看函数create_matrix,它也会使用tm函数。

其次,修改create_matrix功能。例如,添加一个输入参数,如own_stopwords=NULL,并添加以下行:

# existing line
corpus <- Corpus(VectorSource(trainingColumn), 
                     readerControl = list(language = language))
# after that add this new line
if(!is.null(own_stopwords)) corpus <- tm_map(corpus, removeWords, 
                                          words=as.character(own_stopwords))

第三,编写自己的函数,如下所示:

# excluder function
remove_my_stopwords<-function(own_stw, dtm){
  ind<-sapply(own_stw, function(x, words){
    if(any(x==words)) return(which(x==words)) else return(NA)
  }, words=colnames(dtm))
  return(dtm[ ,-c(na.omit(ind))])  
}

让我们来看看它是否有效:

# let´s test it
data(NYTimes)
data <- NYTimes[sample(1:3100, size=10,replace=FALSE),]
matrix <- create_matrix(cbind(data["Title"], data["Subject"]))

head(colnames(matrix), 5)
# [1] "109"         "200th"       "abc"         "amid"        "anniversary"


# let´s consider some "own" stopwords as words above
ostw <- head(colnames(matrix), 5)

matrix2<-remove_my_stopwords(own_stw=ostw, dtm=matrix)

# check if they are still there
sapply(ostw, function(x, words) any(x==words), words=colnames(matrix2))
#109       200th         abc        amid anniversary 
#FALSE       FALSE       FALSE       FALSE       FALSE 

HTH

答案 1 :(得分:0)

您可以在同一列表中添加停用词。例如:

c0 <- tm_map(c0, removeWords, c(stopwords("english"),"mystopwords"))
相关问题