Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - split sentence after words but with maximum of n characters in result

I want to display some text on a scrolling display with a width of 16 characters. To improve readability I want to flip through the text, but not by simply splitting every 16. character, I rather want to split on every ending of a word or punctuation, before the 16 character limit exceeds..

Example:

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

this text shall be converted in a list of strings with 16 characters maximum

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

I started with the regex re.split('(\W+)', text) to get a list of every element (word, punctuation), but I fail combining them.

Can you help me, or at least give me some hints?

Thank you!

like image 338
spky Avatar asked Nov 30 '22 01:11

spky


1 Answers

I'd 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!']

There are lots of options you can play with in the TextWrapper, 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']
like image 92
DSM Avatar answered Dec 06 '22 08:12

DSM