CMS 3D CMS Logo

wordWrappers.py
Go to the documentation of this file.
1 # word-wrap functions
2 # written by Mike Brown
3 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061
4 import math,re
5 from functools import reduce
6 def wrap_always(text, width):
7  """
8  A simple word-wrap function that wraps text on exactly width characters.
9  It doesn't split the text in words.
10  """
11  return '\n'.join([ text[width*i:width*(i+1)] \
12  for i in xrange(int(math.ceil(1.*len(text)/width))) ])
13 
14 def wrap_onspace(text,width):
15  """
16  A word-wrap function that preserves existing line breaks
17  and most spaces in the text. Expects that existing line
18  breaks are posix newlines (\n).
19  """
20  return reduce(lambda line, word, width=width: '%s%s%s' %
21  (line,
22  ' \n'[(len(line[line.rfind('\n')+1:])
23  + len(word.split('\n',1)[0]
24  ) >= width)],
25  word),
26  text.split(' ')
27  )
28 def wrap_onspace_strict(text, width):
29  """
30  Similar to wrap_onspace, but enforces the width constraint:
31  words longer than width are split.
32  """
33  wordRegex = re.compile(r'\S{'+str(width)+r',}')
34  return wrap_onspace(wordRegex.sub(lambda m: wrap_always(m.group(),width),text),width)
35 
36 if __name__ == '__main__':
37  print wrap_always('1234567\ntrtyu43222',5)
38  print ''.join(['-']*5)+'|'
39  print wrap_onspace('1234567\ntrtyu43222',5)
40  print ''.join(['-']*5)+'|'
41  print wrap_onspace_strict('1234567\ntrtyu43222',5)
42  print ''.join(['-']*5)+'|'
def wrap_onspace(text, width)
Definition: wordWrappers.py:14
def wrap_always(text, width)
Definition: wordWrappers.py:6
def wrap_onspace_strict(text, width)
Definition: wordWrappers.py:28
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
#define str(s)