2013-08-31 5 views
4

폭 16 문자의 스크롤 디스플레이에 텍스트를 표시하려고합니다. 가독성을 높이기 위해 텍스트를 넘겨보고 싶지만 단순히 16 문자를 나누지 않고 16 자 제한을 초과 할 때마다 단어 나 구두점의 끝마다 구분하고 싶습니다.Python - 단어 뒤에 문장을 분할하지만 결과에 최대 n 문자가있는 경우

예 :

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

이 텍스트는 내가 모든 요소 (단어, 문장 부호)의 목록을 얻을 수있는 정규식 re.split('(\W+)', text) 시작

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

최대 16 개 문자로 문자열 목록에 변환 할 것이다, 그러나 나는 실패 공동 그들을 저주.

나를 도울 수 있습니까, 아니면 적어도 나에게 약간의 힌트를 줄 수 있습니까?

감사합니다.

답변

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에서 놀 수있는 옵션의 많은 예를 들어, 다음과 같습니다 DSM 제안으로

>>> 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

당신이 굉장합니다! 고맙습니다. – spky

3

, 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

@ 암호 : 사실, 나는 이것에 동의한다. – 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!'] 
관련 문제