【问题标题】:Return up to the first three words返回前三个单词
【发布时间】:2021-09-16 23:11:38
【问题描述】:

试图找到一种方法来返回 R 中的前三个单词。我尝试了 string_r 中的 word 函数,但如果句子至少包含三个单词,它只会返回前三个单词。例如,


sentences <- c("Jane saw a cat", "Jane sat down", "Jane sat", "Jane")

word(sentences, 1, 3)

这将返回Jane saw aJane sat downNANA

我希望它返回前三个单词,即使句子有一个或两个单词。所以我正在寻找的输出是:

这将返回Jane saw aJane sat downJane SatJane

【问题讨论】:

    标签: r tidyverse stringr


    【解决方案1】:

    1) stringr 计算输入的每个组件中的单词数,并将其或 3 中的较小者用作要返回的单词数。

    library(stringr)
    word(sentences, end = pmin(str_count(sentences, "\\w+"), 3))
    ## [1] "Jane saw a"    "Jane sat down" "Jane sat"      "Jane" 
    

    2) stringr solution 2 在末尾附加一些虚拟词,取前 3 个词并剪掉剩下的任何虚拟词。

    sentences %>%
      str_c("@ @ @") %>%
      word(end = 3) %>%
      str_replace(" *@.*", "")
    ## [1] "Jane saw a"    "Jane sat down" "Jane sat"      "Jane"         
    

    3a) Base R 与 (1) 相同的想法可以这样转换为 Base R:

    Word <- function(x, end) do.call("paste", read.table(text = x, fill = TRUE)[1:end])
    
    unname(Vectorize(Word)(sentences, end = pmin(lengths(strsplit(sentences, " ")), 3)))
    ## [1] "Jane saw a"    "Jane sat down" "Jane sat"      "Jane"       
    

    3b) 与 (2) 相同的想法可以像这样转换为基础 R。 Word 来自 (3a)。

    sentences |>
      paste("@ @ @") |>
      Word(end = 3) |>
      sub(pattern = " *@.*", replacement = "")
    ## [1] "Jane saw a"    "Jane sat down" "Jane sat"      "Jane"
    

    更新

    (1) 被简化,旧的 (1) 现在是 (2)。 (3a) 和 (3b) 现在是 Base R 对应项。

    【讨论】:

      【解决方案2】:

      我们可以拆分得到单词

      sapply(strsplit(sentences, " "), \(x) paste(head(x, 3), collapse=" "))
      

      -输出

      [1] "Jane saw a"    "Jane sat down" "Jane sat"      "Jane"       
      

      或者使用正则表达式

      trimws( sub("^((\\w+\\s+){1,3}).*", "\\1", sentences))
      

      -输出

      [1] "Jane saw a" "Jane sat"   "Jane"       "Jane" 
      

      如果我们要使用word,那么可能需要coalesce

      library(stringr)
      library(purrr)
      library(dplyr)
      map(3:1,  word, string = sentences, start = 1) %>%
          exec(coalesce, !!!.)
      [1] "Jane saw a"    "Jane sat down" "Jane sat"      "Jane"  
      

      【讨论】:

        猜你喜欢
        • 2015-12-09
        • 2022-06-22
        • 1970-01-01
        • 1970-01-01
        • 2017-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-27
        相关资源
        最近更新 更多