Saturday, 31 August 2013

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

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

It seems I am too stupid to figure this out by myself:
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!

No comments:

Post a Comment