繁体   English   中英

tm自定义removePunctuation除了标签

[英]tm custom removePunctuation except hashtag

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

这是我的代码:

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

现在的问题是,通过这样做,我也松开了#标签。 有没有办法用tm_map删除标点符号但保留标签?

我维护的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函数,它基本上完成了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"

您可以调整现有的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)

暂无
暂无

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

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