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

时间:2013-08-31 19:01:50

标签: 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!'

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

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

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

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

谢谢!

3 个答案:

答案 0 :(得分: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!']

您可以在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']

答案 1 :(得分:3)

如DSM建议,请查看textwrap。如果您更喜欢坚持使用正则表达式,以下内容将使您成为的一部分:

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',
 '']

(注意最后遗漏的感叹号和空字符串。)

答案 2 :(得分:2)

使用正则表达式:

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