简体   繁体   English

tm自定义removePunctuation除了标签

[英]tm custom removePunctuation except hashtag

I have a Corpus of tweets from twitter. 我有来自twitter的推文语料库。 I clean this corpus (removeWords, tolower, delete URls) and finally also want to remove punctuation. 我清理这个语料库(removeWords,tolower,删除URls),最后还想删除标点符号。

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? 有没有办法用tm_map删除标点符号但保留标签?

The qdap package that I maintain has the strip function to handle this where you can specify characters not to strip: 我维护的qdap包有strip函数来处理这个,你可以指定不剥离的字符:

library(qdap)

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

Here it is applied to a Corpus : 这里它适用于Corpus

library(tm)

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

Also qdap has the sub_holder function that does essentially what Mr. Flick's removeMostPunctuation function does if that's useful 另外qdapsub_holder函数,它基本上完成了Flick先生的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"

You could adapt the existing removePunctuation to suit your needs. 您可以调整现有的removePunctuation以满足您的需求。 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() 当你将它与tm_map一起使用时,但一定要把它包装在content_transformer()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM