Python - splitting sentences after words, but with max n characters as a result

I want to display text on a scrollable display with a width of 16 characters. To improve readability, I want to flip through the text, but not just breaking every 16. character, I rather want to split words or punctuation into each end before the limit of 16 characters exceeds.

Example:

text = 'Hello, this is an example of text shown in the scrolling display. Bla, bla, bla!' 

this text should be converted to a list of lines with a maximum of 16 characters

 result = ['Hello, this is ', 'an example of ', 'text shown in ', 'the scrolling ', 'display. Bla, ', 'bla, bla!'] 

I started with regex re.split('(\W+)', text) to get a list of each element (word, punctuation), but I can't combine them.

Can you help me or at least give me some advice?

Thanks!

+4
source share
3 answers

I would look at the textwrap module:

 >>> text = 'Hello, this is an example of text shown in the scrolling display. Bla, bla, bla!' >>> from textwrap import wrap >>> wrap(text, 16) ['Hello, this is', 'an example of', 'text shown in', 'the scrolling', 'display. Bla,', 'bla, bla!'] 

TextWrapper has many options, for example:

 >>> from textwrap import TextWrapper >>> w = TextWrapper(16, break_long_words=True) >>> w.wrap("this_is_a_really_long_word") ['this_is_a_really', '_long_word'] >>> w = TextWrapper(16, break_long_words=False) >>> w.wrap("this_is_a_really_long_word") ['this_is_a_really_long_word'] 
+13
source

As DSM suggested, look at textwrap . If you prefer to stick with regular expressions, then you get the part from there:

 In [10]: re.findall(r'.{,16}\b', text) Out[10]: ['Hello, this is ', 'an example of ', 'text shown in ', 'the scrolling ', 'display. Bla, ', 'bla, bla', ''] 

(Note the missing exclamation mark and the empty line at the end, though.)

+3
source

Using regex:

 >>> text = 'Hello, this is an example of text shown in the scrolling display. Bla, bla, bla!' >>> pprint(re.findall(r'.{1,16}(?:\s+|$)', text)) ['Hello, this is ', 'an example of ', 'text shown in ', 'the scrolling ', 'display. Bla, ', 'bla, bla!'] 
+2
source

Source: https://habr.com/ru/post/1499957/


All Articles