【问题标题】:Convert punctuation to space将标点符号转换为空格
【发布时间】:2012-07-16 04:36:08
【问题描述】:

我有一堆带有标点符号的字符串,我想将它们转换为空格:

"This is a string. In addition, this is a string (with one more)."

会变成:

"This is a string  In addition  this is a string  with one more  "

我可以通过 stringr 包 (str_replace_all()) 手动执行此操作,一次一个标点符号 (, / . / ! / ( / ) / etc.),但我很好奇是否有我假设使用正则表达式的更快方法。

有什么建议吗?

【问题讨论】:

    标签: regex string r


    【解决方案1】:
    x <- "This is a string. In addition, this is a string (with one more)."
    gsub("[[:punct:]]", " ", x)
    [1] "This is a string  In addition  this is a string  with one more  "
    

    请参阅?gsub 进行这样的快速替换,?regex 了解有关[[:punct:]] 类的详细信息,即

    ‘[:punct:]’ Punctuation characters:
          ‘! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { |
          } ~’.
    

    【讨论】:

      【解决方案2】:

      看看?regex

      library(stringr)
      str_replace_all(x, '[[:punct:]]',' ')
      
      "This is a string  In addition  this is a string  with one more  "
      

      【讨论】:

      • 这不是基础 R 函数,所以需要添加对 stringr 的引用。
      • 我使用的是 OP 声明他们使用 stringrstr_replace_all 的事实。感谢@Josh 的相关编辑。
      猜你喜欢
      • 2016-04-23
      • 2017-07-12
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-13
      相关资源
      最近更新 更多