【问题标题】:How to elegantly split strings in half by word count?如何通过字数优雅地将字符串分成两半?
【发布时间】:2018-01-17 21:52:11
【问题描述】:

我需要按字数将字符串分成两半(当单词数为奇数时,中间的单词应该出现在左侧和右侧)。我还需要知道每个字符串来自哪一侧。

my_question <- data.frame(string_id = c(001, 002, 003), 
    string = (c("how do I split", "how do I split this", "how do I split this string")))

my_answer <- data.frame(string_id = c(001, 002, 003, 001, 002, 003), 
    string = (c("how do", "how do I", "how do I", "I split", "I split this", "split this string")), 
     side = c("R", "R", "R", "L", "L", "L"))

我更喜欢使用 stringr/tidyverse/hadleyverse

【问题讨论】:

  • 你已经尝试过了......
  • 第 1 步使用strsplit 拆分。第 2 步创建索引 1:n/2 和 n/2:n 的向量,其中 n 是第 1 步结果的长度。第一个索引位于左侧,第二个位于右侧。使用pastecollapse=' ' 将两侧重新组合在一起。尝试一下,如果遇到问题,请提出更具体的问题。
  • 另外,请查看 ?strwraplibrary(stringr); ?str_wrap 了解文本换行是如何实现的

标签: r string split tidyverse stringr


【解决方案1】:

我们可以编写一些辅助函数来简化这个过程

library(tidyverse)
word_split <- function(x, side="left", sep=" ") {
  words <- strsplit(as.character(x), sep)
  nwords <- lengths(words)
  if(side=="left") {
    start <- 1
    end <- ceiling(nwords/2)
  } else if (side=="right") {
    start <- ceiling((nwords+1)/2)
    end <- nwords
  }
  cw <- function(words, start, stop) paste(words[start:stop], collapse=sep)
  pmap_chr(list(words, start, end), cw)
}
left_words <- function(..., side) word_split(..., side="left")
right_words <- function(..., side) word_split(..., side="right")

那我们可以用更传统的管道链来分享你想要的结果

my_question %>% mutate(L=left_words(string),
                       R=right_words(string)) %>%
  select(-string) %>% 
  gather(side, string, L:R)

导致

  string_id side            string
1         1    L            how do
2         2    L          how do I
3         3    L          how do I
4         1    R           I split
5         2    R      I split this
6         3    R split this string

【讨论】:

  • 这基本上是我的想法,但我希望看到 OP 做出一些努力。我们一直在说“SO 不是一种代码编写服务”,但随后我们的慷慨就占了上风。
  • 是的。但至少它有一个具有所需输出的可重现示例。这在我的书中有很长的路要走。
猜你喜欢
  • 1970-01-01
  • 2015-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
  • 2011-08-07
  • 1970-01-01
  • 2014-01-12
相关资源
最近更新 更多