将字符串数组拆分为字符串数组的数组

Split an array of strings into an array of arrays of strings

我正在寻找拆分此字符串数组的方法:

["this", "is", "a", "test", ".", "I", "wonder", "if", "I", "can", "parse", "this",
"text", "?", "Without", "any", "errors", "!"]

以标点符号结尾的分组:

[
  ["this", "is", "a", "test", "."],
  ["I", "wonder", "if", "I", "can", "parse", "this", "text", "?"],
  ["Without", "any", "errors", "!"]
]

有没有简单的方法可以做到这一点?迭代数组,将每个索引添加到一个临时数组,并在找到标点符号时将该临时数组附加到容器数组是最明智的方法吗?

我正在考虑使用 slicemap,但我不知道是否可行。

查看 Enumerable#slice_after:

x.slice_after { |e| '.?!'.include?(e) }.to_a

@ndn 给出了这个问题的最佳答案,但我会建议另一种可能适用于其他问题的方法。

像你给的那样的数组一般是通过在空格或标点符号上分割字符串得到的。例如:

s = "this is a test. I wonder if I can parse this text? Without any errors!"
s.scan /\w+|[.?!]/
  #=> ["this", "is", "a", "test", ".", "I", "wonder", "if", "I", "can",
  #    "parse", "this", "text", "?", "Without", "any", "errors", "!"] 

在这种情况下,您可能会发现以其他方式直接操作字符串更为方便。例如,在这里,您可以首先使用 String#split 和正则表达式将字符串 s 分成句子:

r1 = /
     (?<=[.?!]) # match one of the given punctuation characters in capture group 1
     \s*   # match >= 0 whitespace characters to remove spaces
     /x    # extended/free-spacing regex definition mode

a = s.split(r1)
  #=> ["this is a test.", "I wonder if I can parse this text?",
  #    "Without any errors!"] 

然后拆分句子:

r2 = /
     \s+       # match >= 1 whitespace characters
     |         # or
     (?=[.?!]) # use a positive lookahead to match a zero-width string
               # followed by one of the punctuation characters
     /x

b = a.map { |s| s.split(r2) }
  #=> [["this", "is", "a", "test", "."],
  #    ["I", "wonder", "if", "I", "can", "parse", "this", "text", "?"],
  #    ["Without", "any", "errors", "!"]]