2013-08-31 67 views
4

我想在寬度爲16個字符的滾動顯示中顯示一些文本。 爲了提高可讀性,我想翻閱文本,但不是簡單地分割每16個字符,我寧願分割每個字或標點的結尾,在16個字符限制超過之前。Python - 在單詞之後分詞,但在結果中最多有n個字符

示例:

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)讓每一個元素(文字,標點)的名單,但我失敗了合作把它們放在一起。

你能幫我嗎,或者至少給我一些提示?

謝謝!

回答

13

我看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'] 
+0

你是aweseome!謝謝。 – spky

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

+0

你想要我誠實的答案嗎?最好不要堅持正則表達式:)但無論如何謝謝你。 – spky

+0

@spky:其實,我同意你的這個:) – NPE

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!'] 
相關問題