代码之家  ›  专栏  ›  技术社区  ›  Chris T.

删除http中的连字符但保留语料库中的连字符词

  •  2
  • Chris T.  · 技术社区  · 6 年前

    我试图修改一个词干函数,该函数能够1)删除http中的连字符(出现在语料库中),但同时2)保留出现在有意义的连字符表达式中的连字符(例如,耗时、成本高昂等)。 question thread ,代码如下所示:

    # load stringr to use str_replace_all
    require(stringr)
    
    clean.text = function(x)
    {
      # remove rt
      x = gsub("rt ", "", x)
      # remove at
      x = gsub("@\\w+", "", x)
      x = gsub("[[:punct:]]", "", x)
      x = gsub("[[:digit:]]", "", x)
      # remove http
      x = gsub("http\\w+", "", x)
      x = gsub("[ |\t]{2,}", "", x)
      x = gsub("^ ", "", x)
      x = gsub(" $", "", x)
      x = str_replace_all(x, "[^[:alnum:][:space:]'-]", " ")
      #return(x)
    }
    
    # example
    my_text <- "accident-prone"
    new_text <- clean.text(text)
    new_text
    [1] "accidentprone"

    "[^[:alnum:][:space:]'-]" 在代码块的最后一行是罪犯,也删除了 -

    我不知道如何实现我们所期望的产出,如果有人能提供他们在这方面的见解,我将不胜感激。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Wiktor Stribiżew    6 年前

    真正的罪魁祸首是 [[:punct:]] 移除匹配的图案 - 在弦的任何地方。

    clean.text <- function(x)
    {
      # remove rt
      x <- gsub("rt\\s", "", x)
      # remove at
      x <- gsub("@\\w+", "", x)
      x <- gsub("\\b-\\b(*SKIP)(*F)|[[:punct:]]", "", x, perl=TRUE)
      x <- gsub("[[:digit:]]+", "", x)
      # remove http
      x <- gsub("http\\w+", "", x)
      x <- gsub("\\h{2,}", "", x, perl=TRUE)
      x <- trimws(x)
      x <- gsub("[^[:alnum:][:space:]'-]", " ", x)
      return(x)
    }
    

    那么,

    my_text <- "  accident-prone  http://www.some.com  rt "
    new_text <- clean.text(my_text)
    new_text 
    ## => [1] "accident-prone"
    

    看到了吗 R demo .

    • x = gsub("^ ", "", x) x = gsub(" $", "", x) 可以替换为 trimws(x)
    • gsub("\\b-\\b(*SKIP)(*F)|[[:punct:]]", "", x, perl=TRUE) (*SKIP)(*F) )
    • gsub("[^[:alnum:][:space:]'-]", " ", x) str_replace_all(x, "[^[:alnum:][:space:]'-]", " ") .
    • gsub("\\h{2,}", "", x, perl=TRUE) "[ |\t]{2,}" \\s 而不是 \\h 在这里。