【问题标题】:Split sentence based on multiple patterns keeping delimiter基于多个模式保持分隔符的拆分句子
【发布时间】:2021-04-06 02:39:50
【问题描述】:

我有一些句子的分隔模式是“(has|is|thinks)”

我想在第二句中包含分隔符并删除所有尾随空格,如下所示:

mystr1 <- "the bird is now a dog"
mystr2 <- "the small cow thinks like a dog"
mystr3 <- "the fish has become a dog"

结果:

"the bird"          "is now a dog"
"the small cow"     "thinks like a dog"
"the fish"          "has become a dog"

注意: str_split(mystr3, "(has|is|thinks)", n = 2)

导致 "the f" "h has become a dog"

因为“is”是一个分隔符并且是“fish”的一部分

如何最好地做到这一点?

【问题讨论】:

    标签: r regex stringr


    【解决方案1】:

    您可以使用正向前瞻模式来保留分隔符和单词边界,以避免在单词中间分裂。

    split_sent <- function(x) {
        trimws(stringr::str_split(x, '(?=\\b(has|is|thinks)\\b)', n = 2)[[1]])
    }
    
    split_sent(mystr1)
    #[1] "the bird"     "is now a dog"
    split_sent(mystr2)
    #[1] "the small cow"     "thinks like a dog"
    split_sent(mystr3)
    #[1] "the fish"         "has become a dog"
    

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 2012-02-27
      • 1970-01-01
      • 1970-01-01
      • 2011-11-28
      • 2014-12-18
      • 2016-10-30
      • 2019-05-11
      相关资源
      最近更新 更多