a method of dividing English sentences by approximately the number of characters and spaces

Asked 2 years ago, Updated 2 years ago, 37 views

Let's say there are sentences in English that are about 900 characters long.

I'd like to separate this by 300 characters, but in English, if you don't separate it by spaces, the words will be cut off in the middle.

You don't need to separate the sentences with exactly 300 characters, but about 300 characters is fine, so could you tell me how to divide the sentences using Ruby's shortest code or gem in the middle?

ruby

2022-09-30 19:32

3 Answers

It's a little exaggerated, but you can also use ActionView::Helps::TextHelper #word_wrap in the Rails actionview.If you are using Rails, I think you should use this one honestly.

#frozen_string_literal:true
require 'action_view'
include ActionView::Helpers::TextHelper

sample_str=<<EOS
We are about to study the idea of a computational process. Computational processes are abstract beings that inhabit computers. As they evolve, processes manipulate other abstract things called data. The evolution of a process is directed by a pattern of rules called a program. People create programs to direct processes. In effect, we conjure the spirits of the computer with our spells.
EOS

wrapped_str = word_wrap(sample_str, line_width:40)
putswrapped_str

*Sample text is quoted from the beginning of Chapter 1 of SICP


2022-09-30 19:32

I have received a reply from metroplis, so I will share it with you

For example, arr=text.scan(/.{1,300}[\t, .]/m).However, in this case, a string enclosed by "(double quote) or '(single quote) may be split within that range.


2022-09-30 19:32

defans(list, str, split_size, split_hope_size)
  if!str [split_size-1]
    list<<str
  elsif str [split_size-1] == "
    an(list<<str[0...split_size], str[split_size...str.size], split_hope_size, split_hope_size)
  else
    an(list, str, split_size-1, split_hope_size)
  end
end

an([], str.gsub("\n", "", 300, 300).each do|line|
  puts line
end


2022-09-30 19:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.