【问题标题】:Output a string as a sentence将字符串输出为句子
【发布时间】:2017-01-11 14:36:20
【问题描述】:

我有很多这样的字符串:

x1 <- c("Red", "Green", "Blue")
x2 <- c("Red", "Green", "Orange", "Yellow", "Pink")
x3 <- c("Red", "Green")
x4 <- c("Red")
x5 <- c("Red", "Green", "Orange", "Yellow", "Pink", "Blue", "Green")

我想将它们转换成具有这些特征的句子:

  1. 小写
  2. "and" 分隔倒数第二个和最后一个元素
  3. 否则用“,”分隔每个元素
  4. 如果只有 2 个元素,那么它们应该打印为“xx 和 xx”
  5. 如果只有 1 个元素,它们应该打印为“xx”

所以这些字符串上面的字符串应该是这样打印的:

# red, green and blue
# red, green, orange, yellow and pink
# red and green
# red
# red, green, orange, yellow, pink, blue and green

我开始做一个函数来完成上面的事情,这就是我得到的结果:

sentence_string <- function(x){

    x <- tolower(x)

    x <- paste0(x, sep = ,)

    x

}

但无法弄清楚如何实现我想要的输出。有人可以帮忙吗?

【问题讨论】:

    标签: r string


    【解决方案1】:

    仅使用基础 R:

    sentence_string <- function(x){
      l <- length(x)
      if (l == 1) {
        tolower(x)
      } else {
        x <- tolower(x)
        y <- paste(x[-l], collapse = ', ')
        paste0(c(y, x[l]), collapse = ' and ')
      }
    }
    

    给予:

    > sentence_string(x1)
    [1] "red, green and blue"
    > sentence_string(x2)
    [1] "red, green, orange, yellow and pink"
    > sentence_string(x3)
    [1] "red and green"
    > sentence_string(x4)
    [1] "red"
    > sentence_string(x5)
    [1] "red, green, orange, yellow, pink, blue and green"
    

    【讨论】:

      【解决方案2】:

      这些操作我喜欢用stringi

      library(stringi)
      
      get_string <- function(x){
        y <- paste(x, collapse = ', ')
        y1 <- tolower(stri_replace_last_regex(y, ',', ' and'))
        return(y1)
      }
      
      get_string(x1)
      #[1] "red, green and blue"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多