gpt4 book ai didi

ruby - 将字符串拆分为指定大小的 block 而不打断单词

转载 作者:数据小太阳 更新时间:2023-10-29 06:40:35 25 4
gpt4 key购买 nike

我需要根据特定的大小将字符串拆分成 block 。我不能在 block 之间打断单词,所以我需要在添加下一个单词时超过 block 大小并开始下一个单词(如果 block 小于指定大小也没关系)。

这是我的工作代码,但我想找到一种更优雅的方式来做到这一点。

def split_into_chunks_by_size(chunk_size, string)
string_split_into_chunks = [""]
string.split(" ").each do |word|
if (string_split_into_chunks[-1].length + 1 + word.length > chunk_size)
string_split_into_chunks << word
else
string_split_into_chunks[-1] << " " + word
end
end
return string_split_into_chunks
end

最佳答案

怎么样:

str = "split a string into chunks according to a specific size. Seems easy enough, but here is the catch: I cannot be breaking words between chunks, so I need to catch when adding the next word will go over chunk size and start the next one (its ok if a chunk is less than specified size)." 
str.scan(/.{1,25}\W/)
=> ["split a string into ", "chunks according to a ", "specific size. Seems easy ", "enough, but here is the ", "catch: I cannot be ", "breaking words between ", "chunks, so I need to ", "catch when adding the ", "next word will go over ", "chunk size and start the ", "next one (its ok if a ", "chunk is less than ", "specified size)."]

@sawa 评论后更新:

str.scan(/.{1,25}\b|.{1,25}/).map(&:strip)

这样更好,因为它不需要字符串以\W 结尾

它会处理超过指定长度的单词。实际上它会拆分它们,但我认为这是期望的行为

关于ruby - 将字符串拆分为指定大小的 block 而不打断单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15401326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com