Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tm custom removePunctuation except hashtag

I have a Corpus of tweets from twitter. I clean this corpus (removeWords, tolower, delete URls) and finally also want to remove punctuation.

Here is my code:

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

The problem now is, that by doing so I also loose the hashtag (#). Is there a way to remove punctuation with tm_map but remain the hashtag?

like image 220
feder80 Avatar asked Jan 14 '15 19:01

feder80


1 Answers

You could adapt the existing removePunctuation to suit your needs. For example

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)
    }
}

Which will give you

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

and when you use it with tm_map, but sure to wrap it in content_transformer()

tweetCorpus <- tm_map(tweetCorpus, content_transformer(removeMostPunctuation),
    preserve_intra_word_dashes = TRUE)
like image 76
MrFlick Avatar answered Sep 27 '22 22:09

MrFlick