真正的罪魁祸首是
[[:punct:]]
移除匹配的图案
-
在弦的任何地方。
clean.text <- function(x)
{
# remove rt
x <- gsub("rt\\s", "", x)
# remove at
x <- gsub("@\\w+", "", x)
x <- gsub("\\b-\\b(*SKIP)(*F)|[[:punct:]]", "", x, perl=TRUE)
x <- gsub("[[:digit:]]+", "", x)
# remove http
x <- gsub("http\\w+", "", x)
x <- gsub("\\h{2,}", "", x, perl=TRUE)
x <- trimws(x)
x <- gsub("[^[:alnum:][:space:]'-]", " ", x)
return(x)
}
那么,
my_text <- " accident-prone http://www.some.com rt "
new_text <- clean.text(my_text)
new_text
## => [1] "accident-prone"
看到了吗
R demo
.
-
x = gsub("^ ", "", x)
和
x = gsub(" $", "", x)
可以替换为
trimws(x)
-
gsub("\\b-\\b(*SKIP)(*F)|[[:punct:]]", "", x, perl=TRUE)
(*SKIP)(*F)
)
-
gsub("[^[:alnum:][:space:]'-]", " ", x)
str_replace_all(x, "[^[:alnum:][:space:]'-]", " ")
.
-
gsub("\\h{2,}", "", x, perl=TRUE)
"[ |\t]{2,}"
\\s
而不是
\\h
在这里。