fed*_*r80 5 customization text-processing r punctuation tm
我有来自twitter的推文语料库.我清理这个语料库(removeWords,tolower,删除URls),最后还想删除标点符号.
这是我的代码:
tweetCorpus <- tm_map(tweetCorpus, removePunctuation, preserve_intra_word_dashes = TRUE)
Run Code Online (Sandbox Code Playgroud)
现在的问题是,通过这样做,我也松开了#标签.有没有办法用tm_map删除标点符号但保留标签?
您可以调整现有的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)
}
}
Run Code Online (Sandbox Code Playgroud)
哪个会给你
removeMostPunctuation("hello #hastag @money yeah!! o.k.")
# [1] "hello #hastag money yeah ok"
Run Code Online (Sandbox Code Playgroud)
当你将它与tm_map一起使用时,但一定要把它包装好 content_transformer()
tweetCorpus <- tm_map(tweetCorpus, content_transformer(removeMostPunctuation),
preserve_intra_word_dashes = TRUE)
Run Code Online (Sandbox Code Playgroud)
我维护的qdap包具有strip处理此功能的功能,您可以在其中指定不剥离的字符:
library(qdap)
strip("hello #hastag @money yeah!! o.k.", char.keep="#")
Run Code Online (Sandbox Code Playgroud)
这里适用于Corpus:
library(tm)
tweetCorpus <- Corpus(VectorSource("hello #hastag @money yeah!! o.k."))
tm_map(tweetCorpus, content_transformer(strip), char.keep="#")
Run Code Online (Sandbox Code Playgroud)
此外,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"
Run Code Online (Sandbox Code Playgroud)