首页 文章

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

提问于
浏览
6

使用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 回答

  • 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

  • 0

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

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

相关问题