【问题标题】:How to remove parentheses with words inside by tm packages ?如何通过 tm 包删除带有单词的括号?
【发布时间】:2015-10-16 11:08:17
【问题描述】:

假设我在这样的文档中有部分文本:

"Other segment comprised of our active pharmaceutical ingredient (API) business,which..."

我想删除“(API)”,需要在此之前完成

corpus <- tm_map(corpus, removePunctuation) 

删除“(API)”后,应该如下所示:

"Other segment comprised of our active pharmaceutical ingredient business,which..."

我找了很久,但我只能找到关于删除括号的答案,我不想出现在语料库中的单词。

我真的需要有人给我一些提示。

【问题讨论】:

    标签: r tm punctuation


    【解决方案1】:

    您可以使用更智能的标记器,例如 quanteda 包中的标记器,其中removePunct = TRUE 将自动删除括号。

    quanteda::tokenize(txt, removePunct = TRUE)
    ## tokenizedText object from 1 document.
    ## Component 1 :
    ##  [1] "Other"          "segment"        "comprised"      "of"             "our"            ## "active"         "pharmaceutical"
    ##  [8] "ingredient"     "API"            "business"       "which"         
    

    添加:

    如果您想首先标记文本,那么您需要 lapplygsub,直到我们在 quanteda 中将正则表达式 valuetype 添加到 removeFeatures.tokenizedTexts()。但这会起作用:

    # tokenized version
    require(quanteda)
    toks <- tokenize(txt, what = "fasterword", simplify = TRUE)
    toks[-grep("^\\(.*\\)$", toks)]
    ## [1] "Other"             "segment"           "comprised"         "of"                "our"               "active"           
    ## [7] "pharmaceutical"    "ingredient"        "business,which..."
    

    如果您只是想删除问题中的括号表达式,那么您不需要 tmquanteda

    # exactly as in the question
    gsub("\\s(\\(\\w*\\))(\\s|[[:punct:]])", "\\2", txt)
    ## [1] "Other segment comprised of our active pharmaceutical ingredient business,which..."
    
    # with added punctuation
    txt2 <- "ingredient (API), business,which..."
    txt3 <- "ingredient (API).  New sentence..."
    gsub("\\s(\\(\\w*\\))(\\s|[[:punct:]])", "\\2", txt2)
    ## [1] "ingredient, business,which..."
    gsub("\\s(\\(\\w*\\))(\\s|[[:punct:]])", "\\2", txt3)
    ## [1] "ingredient.  New sentence..."
    

    较长的正则表达式还可以捕获括号表达式结束句子或后跟附加标点符号(例如逗号)的情况。

    【讨论】:

    • 感谢您的回答,但我需要删除的不仅仅是括号。里面的字也需要去掉。
    • 好的,我已经修改了答案,见上文。
    • @JohnChou 感谢您告诉我。一个赞成票将是一个很好的感谢。
    • “如果你想先对文本进行标记,那么你需要使用 gsub 直到我们在 quanteda 中为 removeFeatures.tokenizedTexts() 添加一个正则表达式 valuetype。” 我不太懂,能详细解释一下吗?谢谢!
    【解决方案2】:

    如果只是单个单词,那么(未经测试)怎么样:

    removeBracketed <- content_transformer(function(x, ...) {gsub("\\(\\w+\\)", "", x)})
    tm_map(corpus, removeBracketed)
    

    【讨论】:

      猜你喜欢
      • 2010-12-29
      • 1970-01-01
      • 2022-12-17
      • 2015-11-20
      • 1970-01-01
      • 2011-04-14
      • 2022-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多