TM自定义去除标点符号,但保留井号。

5

我有一些来自Twitter的推文语料库。我需要清理这个语料库(删除单词,转换为小写字母,删除URL),最后还想要删除标点符号。

以下是我的代码:

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

现在的问题是,这样做会导致我失去标签(#)。有没有一种方法可以使用tm_map删除标点符号但保留标签?
2个回答

8
你可以根据需要修改现有的 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)

这个程序有些晦涩,使用哨兵\001、\002来临时保护'#'和'-'以避免被移除。您是否更喜欢不包含这些符号扩展[[:punct:]],以避免破坏Unicode标点符号? - smci

8
我维护的 qdap 包具有 strip 函数,可以处理这个问题,您可以指定不需要去除的字符:
library(qdap)

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

这里是应用于语料库的示例:

library(tm)

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

此外,qdap库中有sub_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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接