Python - 在单词之后拆分句子,但结果中最多包含n个字符

spk*_*pky 4 python regex string python-2.7

我想在滚动显示上显示一些宽度为16个字符的文本.为了提高可读性,我想翻阅文本,但不是简单地分割每16个字符,我宁愿在16字符限制超过之前拆分单词或标点符号的每个结尾.

例:

text = 'Hello, this is an example of text shown in the scrolling display. Bla, bla, bla!'
Run Code Online (Sandbox Code Playgroud)

该文本应转换为最多16个字符的字符串列表

result = ['Hello, this is ', 'an example of ', 'text shown in ', 'the scrolling ', 'display. Bla, ', 'bla, bla!']
Run Code Online (Sandbox Code Playgroud)

我从正则表达式re.split('(\W+)', text)开始获取每个元素(单词,标点符号)的列表,但我没有将它们组合起来.

你能帮助我,或者至少给我一些提示吗?

谢谢!

DSM*_*DSM 16

我看一下textwrap模块:

>>> 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!']
Run Code Online (Sandbox Code Playgroud)

您可以在TextWrapper中使用许多选项,例如:

>>> 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']
Run Code Online (Sandbox Code Playgroud)