我有一些来自Twitter的推文语料库。我需要清理这个语料库(删除单词,转换为小写字母,删除URL),最后还想要删除标点符号。
以下是我的代码:
tweetCorpus <- tm_map(tweetCorpus, removePunctuation, preserve_intra_word_dashes = TRUE)
现在的问题是,这样做会导致我失去标签(#)。有没有一种方法可以使用tm_map删除标点符号但保留标签?
我有一些来自Twitter的推文语料库。我需要清理这个语料库(删除单词,转换为小写字母,删除URL),最后还想要删除标点符号。
以下是我的代码:
tweetCorpus <- tm_map(tweetCorpus, removePunctuation, preserve_intra_word_dashes = TRUE)
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)
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"
[[:punct:]]
,以避免破坏Unicode标点符号? - smci