【问题标题】:R function to start new line every n words?R函数每n个单词开始换行?
【发布时间】:2020-08-29 13:35:56
【问题描述】:

我想创建一个 R 函数,在字符串中的每 n 个单词之后插入一个“\n”(其中 n 是一个参数)。

例如

startstring <- "I like to eat fried potatoes with gravy for dinner."

myfunction(startstring, 4)

会给:

"I like to eat\nfried potatoes with gravy\nfor dinner."

我相信要做到这一点,我需要将字符串分成几个部分,每个部分长 n 个单词,然后用分隔符“\n”将它们粘贴在一起。但是我不知道如何进行初始拆分步骤。

谁能给点建议?

【问题讨论】:

  • 看看 Base R 中的strsplit()

标签: r string function newline


【解决方案1】:

你可以用正则表达式解决这个问题,或者用这个可恶的方法:

words = strsplit(startstring, ' ')[[1L]]
splits = cut(seq_along(words), breaks = seq(0L, length(words) + 4L, by = 4L))
paste(lapply(split(words, splits), paste, collapse = ' '), collapse = '\n')

但是对于大多数实用应用程序来说,更好的方法是使用strwrap 以给定的列长度包装文本,而不是按字数计算:

paste(strwrap(startstring, 20), collapse = '\n')

【讨论】:

  • 谢谢,这实际上对我需要的东西更有用!
【解决方案2】:

您可以使用以下代码:

gsub("([a-z0-9]* [a-z0-9]* [a-z0-9]* [a-z0-9]*) ", "\\1\n", startstring)

【讨论】:

  • 看起来我采取了与您相同的方法,我花了一点时间才意识到它仅适用于最后一个“单词”之后的尾随空格。
  • 看看我编辑的答案,根据 OP 所需的输出,尾随空格应该在括号之外。
  • 是的,你是对的兄弟.....@DanielO 谢谢.. 编辑了我的答案。
【解决方案3】:

您可以使用gsub 创建一个R 函数,该函数在每n 个单词后插入一个“\n”,其中n 是一个参数。

fun <- function(str, n) {gsub(paste0("((\\w+ +){",n-1,"}\\w+) +")
 , "\\1\\\n", str, perl=TRUE)}
fun(startstring, 4)
#[1] "I like to eat\nfried potatoes with gravy\nfor dinner."
fun(startstring, 2)
#[1] "I like\nto eat\nfried potatoes\nwith gravy\nfor dinner."

或使用strsplit:

fun2 <- function(str, n) {suppressWarnings(paste(mapply(paste0
  , strsplit(str, " ")[[1]], c(rep(" ",n-1),"\n")), collapse = ""))}
fun2(startstring, 4)
#[1] "I like to eat\nfried potatoes with gravy\nfor dinner. "

【讨论】:

    【解决方案4】:

    这使用空格分隔单词,在Base-R

    gsub("(\\S* \\S* \\S* \\S*) ","\\1\n",startstring) 
    [1] "I like to eat\nfried potatoes with gravy\nfor dinner."
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      • 2016-02-06
      • 2018-04-15
      • 2014-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多