【问题标题】:How to split a character element to create a vector based on \n position如何根据 \n 位置拆分字符元素以创建向量
【发布时间】:2021-02-24 21:49:56
【问题描述】:

我有一个这样的角色元素...

element <- "\n\n\n\nPrivate trip\n\n\nPrivate trip \n\n\n\nFull Day Trip \n\n\n\n\n\nFREE Cancellation 3 days notice \n\n"

我想将元素拆分以创建一个向量,以便每个向量元素都是\n 之间的短语。期望的结果是这样的元素

result <- c("Private trip", "Private trip", "Full Day Trip", "FREE Cancellation 3 days notice")

我觉得这项任务的困难在于每个短语之间没有固定数量的\n。我试过了

strsplit(element, "\n", fixed = FALSE, perl = FALSE, useBytes = FALSE)

但这给了我一个包含许多空元素的列表。我可以解决这个问题,但我觉得可能有更有效的方法。

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以指定一个或多个 (\n+) 以及零个或多个空格 (\\s*)

    out <- strsplit(element, "\\s*\n+\\s*")[[1]]
    out[nzchar(out)]
    #[1] "Private trip"                    "Private trip"                    "Full Day Trip"                  
    #[4] "FREE Cancellation 3 days notice"
    

    【讨论】:

      【解决方案2】:

      read.csv

      > trimws(unlist(read.csv(text = element, header = FALSE), use.names = FALSE))
      [1] "Private trip"                    "Private trip"
      [3] "Full Day Trip"                   "FREE Cancellation 3 days notice"
      

      regmatches

      > trimws(unlist(regmatches(element, gregexpr("(\\w+\\s?)+", element))))
      [1] "Private trip"                    "Private trip"
      [3] "Full Day Trip"                   "FREE Cancellation 3 days notice"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-28
        • 1970-01-01
        • 2014-12-19
        • 2020-03-18
        • 1970-01-01
        相关资源
        最近更新 更多