【问题标题】:Removing punctuation except for apostrophes AND intra-word dashes with gsub in R WITHOUT accidently concatenating two words在 R 中使用 gsub 删除撇号和单词内破折号以外的标点符号,而不会意外连接两个单词
【发布时间】:2016-01-08 18:13:08
【问题描述】:

我一直在寻找有关 Stackoverflow 的解决方案并在 R (RStudio) 中试验了几个小时。我知道如何删除标点符号,同时使用 gsub(不是 tm 包,但我想知道是否有人可以提供有关此操作的提示)与以下问题同时进行)。我想知道如何防止将单词与 gsub 或任何其他正则表达式过程连接起来,而我曾经删除过的标点符号在哪里。到目前为止,这是我能做的最好的:

x <-"Good luck!!!!SPRINT I like good deals. I can't lie brand-new stuff---- excites me got&&&&& to say yo, At&t why? a* dash-- apostrophe's''' I can do all-day. But preventing%%%%concatenating  is a new**$ballgame but----why--- not?"

gsub("(\\w['&-]\\w)|[[:punct:]]", "\\1", x, perl=TRUE) 

#[1] "Good luckSPRINT I like good deals I can't lie brand-new stuff excites me got to say yo At&t why a dash apostrophe's I can do all-day But preventingconcatenating  is a newballgame butwhy not"

有什么想法吗?顺便说一句,这个问题的目的是将解决方案应用于数据框列或社交媒体帖子的语料库。

【问题讨论】:

    标签: regex r gsub


    【解决方案1】:

    您可以在一个函数中只保留前导/尾随空格:

    gsub("[[:punct:]]* *(\\w+[&'-]\\w+)|[[:punct:]]+ *| {2,}", " \\1", x)
    # [1] "Good luck SPRINT I like good deals I can't lie brand-new stuff excites me got to say yo At&t why a dash apostrophe's I can do all-day But preventing concatenating is a new ballgame but why not "
    

    如果你能够使用 qdapRegex 包,你可以这样做:

    library(qdapRegex)
    rm_default(x, pattern = "[^ a-zA-Z&'-]|[&'-]{2,}", replacement = " ")
    # [1] "Good luck SPRINT I like good deals I can't lie brand-new stuff excites me got to say yo At&t why a dash apostrophe's I can do all-day But preventing concatenating is a new ballgame but why not"
    

    【讨论】:

      【解决方案2】:

      你可以:

      1. 匹配每个标点符号前后的所有空格,并在替换中使用 1 个空格
      2. 限制[-'&amp;] 仅在非单词边界\B 之后或之前匹配

      正则表达式:

      \s*(?:(?:\B[-'&]+|[-'&]+\B|[^-'&[:^punct:]]+)\s*)+
      
      • 请注意,我在 [^-'&amp;[:^punct:]] 中使用双重否定将 -'&amp; 从 POSIX 类 [:punct:] 中排除

      替换:

      " "   (1 space)
      

      regex101 Demo

      代码:

      x <-"Good luck!!!!SPRINT I like good deals. I can't lie brand-new stuff---- excites me got&&&&& to say yo, At&t why? a* dash-- apostrophe's''' I can do all-day. But preventing%%%%concatenating  is a new**$ballgame but----why--- not?"
      
      gsub("\\s*(?:(?:\\B[-'&]+|[-'&]+\\B|[^-'&[:^punct:]]+)\\s*)+", " ", x, perl=TRUE)
      
      #[1] "Good luck SPRINT I like good deals I can't lie brand-new stuff excites me got to say yo At&t why a dash apostrophe's I can do all-day But preventing concatenating  is a new ballgame but why not "
      

      ideone Demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-07
        • 2012-01-31
        • 1970-01-01
        • 2020-06-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多