首页 > 解决方案 > 我想用空格替换双标点

问题描述

我写了以下代码,但它不起作用

replacePunctuation <- function(x) {
                gsub("[[:punct:]]+" , " " , x)
                }

sms_data_corpus_clean <- tm_map(sms_data_corpus_clean, replacePunctuation)
**I installed and loaded the library tm

注意:目的是避免使用以下示例中的标点符号:

Are you still.....there?

使用

sms_data_corpus_clean <- tm_map(sms_data_corpus_clean, removePunctuation)

结果,我们将这两个词连接起来

   Are you stillthere

标签: rregexcorpuspunctuation

解决方案


我认为您可以在此处使用stringr'str_replace功能-

library(stringr)

replacePunctuation <- function(x){
  # if there are multiple punctuations replace them
  str_replace(x, pattern = "[[:punct:]]{2,}", " ")
}

sample_data <- c("2 or more punctuations - Are you still.....there?", 
                   "only one punctuation - Are you still, here?")


replacePunctuation(sample_data)
#> [1] "2 or more punctuations - Are you still there?"
#> [2] "only one punctuation - Are you still, here?"

由 reprex 包(v0.2.0)于 2018 年 8 月 23 日创建。


推荐阅读