Go to the documentation of this file.00001
00002
00003
00004 import math,re
00005 def wrap_always(text, width):
00006 """
00007 A simple word-wrap function that wraps text on exactly width characters.
00008 It doesn't split the text in words.
00009 """
00010 return '\n'.join([ text[width*i:width*(i+1)] \
00011 for i in xrange(int(math.ceil(1.*len(text)/width))) ])
00012
00013 def wrap_onspace(text,width):
00014 """
00015 A word-wrap function that preserves existing line breaks
00016 and most spaces in the text. Expects that existing line
00017 breaks are posix newlines (\n).
00018 """
00019 return reduce(lambda line, word, width=width: '%s%s%s' %
00020 (line,
00021 ' \n'[(len(line[line.rfind('\n')+1:])
00022 + len(word.split('\n',1)[0]
00023 ) >= width)],
00024 word),
00025 text.split(' ')
00026 )
00027 def wrap_onspace_strict(text, width):
00028 """
00029 Similar to wrap_onspace, but enforces the width constraint:
00030 words longer than width are split.
00031 """
00032 wordRegex = re.compile(r'\S{'+str(width)+r',}')
00033 return wrap_onspace(wordRegex.sub(lambda m: wrap_always(m.group(),width),text),width)
00034
00035 if __name__ == '__main__':
00036 print wrap_always('1234567\ntrtyu43222',5)
00037 print ''.join(['-']*5)+'|'
00038 print wrap_onspace('1234567\ntrtyu43222',5)
00039 print ''.join(['-']*5)+'|'
00040 print wrap_onspace_strict('1234567\ntrtyu43222',5)
00041 print ''.join(['-']*5)+'|'