2015-01-14 128 views
4

我有一个来自twitter的推文语料库。我清理这个语料库(removeWords,tolower,删除URls),最后还想删除标点符号。tm自定义删除标点符号,除了#标签

这里是我的代码:

tweetCorpus <- tm_map(tweetCorpus, removePunctuation, preserve_intra_word_dashes = TRUE) 

现在的问题是,如果这样做我也失去了包括hashtag(#)。有没有办法用tm_map去除标点符号,但仍然是标签?

回答

7

您可以调整现有的removePunctuation以适合您的需求。例如

removeMostPunctuation<- 
function (x, preserve_intra_word_dashes = FALSE) 
{ 
    rmpunct <- function(x) { 
     x <- gsub("#", "\002", x) 
     x <- gsub("[[:punct:]]+", "", x) 
     gsub("\002", "#", x, fixed = TRUE) 
    } 
    if (preserve_intra_word_dashes) { 
     x <- gsub("(\\w)-(\\w)", "\\1\001\\2", x) 
     x <- rmpunct(x) 
     gsub("\001", "-", x, fixed = TRUE) 
    } else { 
     rmpunct(x) 
    } 
} 

,这将给你

removeMostPunctuation("hello #hastag @money yeah!! o.k.") 
# [1] "hello #hastag money yeah ok" 

,当你与tm_map使用它,但请务必将它content_transformer()

tweetCorpus <- tm_map(tweetCorpus, content_transformer(removeMostPunctuation), 
    preserve_intra_word_dashes = TRUE) 
+0

谢谢,这工作! – feder80

+0

这是相当神秘的与额外的步骤使用哨兵\ 001,\ 002临时保护'#',' - '从删除。您是否更愿意不使用这些符号来扩展'[[:punct:]]',以避免打破Unicode标点符号? – smci

8

qdap包,我维护有strip函数来处理这个你可以指定字符不去掉的地方:

library(qdap) 

strip("hello #hastag @money yeah!! o.k.", char.keep="#") 

这适用于Corpus

library(tm) 

tweetCorpus <- Corpus(VectorSource("hello #hastag @money yeah!! o.k.")) 
tm_map(tweetCorpus, content_transformer(strip), char.keep="#") 

而且qdapsub_holder函数,它基本上是弗里克先生的removeMostPunctuation的功能是什么,如果这是有用的

removeMostPunctuation <- function(text, keep = "#") { 
    m <- sub_holder(keep, text) 
    m$unhold(strip(m$output)) 
} 

removeMostPunctuation("hello #hastag @money yeah!! o.k.") 

## "hello #hastag money yeah ok"