【问题标题】:Removing punctuation except for apostrophes AND intra-word dashes in R删除 R 中除撇号和单词内破折号以外的标点符号
【发布时间】:2014-07-03 09:59:43
【问题描述】:

我知道如何分别去掉标点和保留撇号:

gsub( "[^[:alnum:]']", " ", db$text )  

或如何在 tm 包中保留字内破折号:

removePunctuation(db$text, preserve_intra_word_dashes = TRUE)

但我找不到同时做这两个的方法。例如如果我的原句是:

"Interested in energy/the environment/etc.? Congrats to our new e-board! Ben, Nathan, Jenny, and Adam, y'all are sure to lead the club in a great direction next year! #obama #swag"

我希望它是:

"Interested in energy the environment etc Congrats to our new e-board Ben Nathan Jenny and Adam y'all are sure to lead the club in a great direction next year obama swag"

当然,会有多余的空格,但我可以稍后删除它们。

我会很感激你的帮助。

【问题讨论】:

    标签: string r text


    【解决方案1】:

    使用character classes

    gsub("[^[:alnum:]['-]", " ", db$text)
    
    ## "Interested in energy the environment etc Congrats to our new e-board Ben Nathan Jenny and Adam y'all are sure to lead the club in a great direction next year obama swag"
    

    【讨论】:

    • 感谢您提供简短而好的解决方案。它在我拥有的一小部分推文上运行良好,但是当我在超过 200,000 条推文的样本上运行它时,我得到一个错误:找不到函数“&
    • 我不知道这个错误是由什么引起的。我认为它来自您代码的其他部分。不,gsub 是基础 R,不需要额外的包
    • 你说的太对了,谢谢——当然是一个愚蠢的错字。
    • 不幸的是,这种方法不能区分单词内破折号和单词破折号。在一个字符串中:string1
    • 我通过2个步骤解决了这个问题:首先删除单词之间的破折号:gsub(" - ", " ", string1,perl = TRUE),然后使用上述解决方案。
    【解决方案2】:

    我喜欢David Arenberg's 的回答。如果您需要其他方式,可以尝试:

    library(qdap)
    
    text <- "Interested in energy/the environment/etc.? Congrats to our new e-board! Ben, Nathan, Jenny, and Adam, y'all are sure to lead the club in a great direction next year! #obama #swag"
    
    gsub("/", " ",strip(text, char.keep=c("-","/"), apostrophe.remove=F,lower.case=F))
    #[1] "Interested in energy the environment etc Congrats to our new e-board Ben Nathan Jenny and Adam y'all are sure to lead the club in a great direction next year obama swag"
    

    或

    library(gsubfn)
     clean(gsubfn("[[:punct:]]", function(x) ifelse(x=="'","'",ifelse(x=="-","-"," ")),text))
    #[1] "Interested in energy the environment etc Congrats to our new e-board Ben Nathan Jenny and Adam y'all are sure to lead the club in a great direction next year obama swag"
    

    clean 来自qdap。用于去除转义字符和空格

    【讨论】:

      猜你喜欢
      • 2016-01-08
      • 2012-01-31
      • 2016-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      • 2015-07-07
      相关资源
      最近更新 更多