【问题标题】:Remove punctuation in R but leave punctuation/"sentence markers" "!", ".", "?" at the end of a sentence删除 R 中的标点符号,但保留标点符号/“句子标记”“!”、“。”、“?”在句末
【发布时间】:2020-06-05 20:13:16
【问题描述】:

我目前正在尝试在我正在使用的文本语料库上创建基于句子的 LDA。 为了检测句子并拆分它们,我使用了openNLP 包中的sent_detect() 函数。

但是,我正在使用的数据集非常不干净,并且包含许多其他“标点符号”,我想在使用 sent_detect() 函数之前删除这些“标点符号”。

通常,我会在文本语料库上使用以下代码(来自tm 包)来删除标点符号:
text.corpus <- tm_map(text.corpus, removePunctuation)

然而,这个函数会删除所有类型的标点符号,包括 ".", "?", "!", "|" @使用的987654326@ 检测句子的功能。因此,将文本分成单独的句子会破坏我的目标。

有没有办法使用上述tm_map() 函数删除标点符号但排除特定的“句子指示符”(*“.”、“?”、“!”、“|”**)?

这是一个文本示例:

不好笑; - 我根本不喜欢这部电影/电影(因为演员很糟糕)。但是,我真的很喜欢这里的风景!

通常情况下,上面的removePunctuation会删除所有标点符号并留下以下句子:

不好笑我根本不喜欢这部电影,因为演员很糟糕,但我真的很喜欢这里的风景

但是,我最终想要的是:

不好笑我根本不喜欢这部电影,因为演员很糟糕。但是我真的很喜欢这里的风景!

谢谢!

Ps:使用 openNLP 包不是必须的,我也愿意接受任何其他解决方案!

【问题讨论】:

    标签: r gsub data-cleaning lda topic-modeling


    【解决方案1】:

    您可以使用gsub 将要删除的所有字符定义为模式,将它们与交替标记| 连接,并确保使用@987654325 正确转义() 等元字符@,并在替换参数中用"" 替换模式——也就是说,什么都没有:

    gsub(";|- |/ |,|\\(|\\)", "", s)
    [1] "not funny i did not like the movie film at all since the actors were terrible. however i really enjoyed the scenery!"
    

    数据:

    s <- "not funny; - i did not like the movie / film at all (since the actors were terrible). however, i really enjoyed the scenery!"
    

    【讨论】:

      【解决方案2】:

      使用 stringr 和一个 not-not-statement(感谢 Chris Ruehlemann 的评论):

      s <- "not funny; - i did not like the movie / film at all (since the actors were terrible). however, i really enjoyed the scenery!"
      
      str_remove_all(s, "[^[^[[:punct:]]]!|.|?]")
      [1] "not funny  i did not like the movie  film at all since the actors were terrible. however i really enjoyed the scenery!"
      

      【讨论】:

      • 我实际上不知道为什么这对 str_remove_all 有效而对 gsub 失败。
      • 此解决方案在已删除字符且不需要在字符类中转义的点留下双空格字符:str_remove_all(s, "[^[^[[:punct:]]]!|.|?]") 提示相同的结果。
      猜你喜欢
      • 2014-06-20
      • 1970-01-01
      • 2021-03-18
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      • 2014-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多