【问题标题】:tm custom removePunctuation except hashtagtm 自定义 removePunctuation 除了标签
【发布时间】:2015-01-14 19:58:54
【问题描述】:

我有一个来自 twitter 的推文语料库。我清理了这个语料库(removeWords、tolower、delete URls),最后还想删除标点符号。

这是我的代码:

tweetCorpus <- tm_map(tweetCorpus, removePunctuation, preserve_intra_word_dashes = TRUE)

现在的问题是,这样做我也会丢失主题标签 (#)。有没有办法用 tm_map 删除标点符号但保留主题标签?

【问题讨论】:

    标签: r customization text-processing tm punctuation


    【解决方案1】:

    您可以调整现有的 removePunctuation 以满足您的需求。例如

    removeMostPunctuation<-
    function (x, preserve_intra_word_dashes = FALSE) 
    {
        rmpunct <- function(x) {
            x <- gsub("#", "\002", x)
            x <- gsub("[[:punct:]]+", "", x)
            gsub("\002", "#", x, fixed = TRUE)
        }
        if (preserve_intra_word_dashes) { 
            x <- gsub("(\\w)-(\\w)", "\\1\001\\2", x)
            x <- rmpunct(x)
            gsub("\001", "-", x, fixed = TRUE)
        } else {
            rmpunct(x)
        }
    }
    

    哪个会给你

    removeMostPunctuation("hello #hastag @money yeah!! o.k.")
    # [1] "hello #hastag money yeah ok"
    

    当你将它与 tm_map 一起使用时,但一定要把它包裹在 content_transformer()

    tweetCorpus <- tm_map(tweetCorpus, content_transformer(removeMostPunctuation),
        preserve_intra_word_dashes = TRUE)
    

    【讨论】:

    • 这很神秘,额外的步骤是使用标记 \001,\002 来临时保护 '#','-' 不被删除。您是否不想在没有这些符号的情况下简单地扩展 [[:punct:]],以避免破坏 Unicode 标点符号?
    【解决方案2】:

    我维护的 qdap 包具有 strip 函数来处理此问题,您可以指定不剥离的字符:

    library(qdap)
    
    strip("hello #hastag @money yeah!! o.k.", char.keep="#")
    

    这里应用于Corpus

    library(tm)
    
    tweetCorpus <- Corpus(VectorSource("hello #hastag @money yeah!! o.k."))
    tm_map(tweetCorpus, content_transformer(strip), char.keep="#")
    

    qdap 也有 sub_holder 函数,如果有用的话,基本上可以完成 Flick 先生的 removeMostPunctuation 函数的作用

    removeMostPunctuation <- function(text, keep = "#") {
        m <- sub_holder(keep, text)
        m$unhold(strip(m$output))
    }
    
    removeMostPunctuation("hello #hastag @money yeah!! o.k.")
    
    ## "hello #hastag money yeah ok"
    

    【讨论】:

      猜你喜欢
      • 2014-01-03
      • 2013-02-06
      • 1970-01-01
      • 2012-07-13
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2011-10-15
      相关资源
      最近更新 更多