CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
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 def wrap_always(text, width):
6  """
7  A simple word-wrap function that wraps text on exactly width characters.
8  It doesn't split the text in words.
9  """
10  return '\n'.join([ text[width*i:width*(i+1)] \
11  for i in xrange(int(math.ceil(1.*len(text)/width))) ])
12 
13 def wrap_onspace(text,width):
14  """
15  A word-wrap function that preserves existing line breaks
16  and most spaces in the text. Expects that existing line
17  breaks are posix newlines (\n).
18  """
19  return reduce(lambda line, word, width=width: '%s%s%s' %
20  (line,
21  ' \n'[(len(line[line.rfind('\n')+1:])
22  + len(word.split('\n',1)[0]
23  ) >= width)],
24  word),
25  text.split(' ')
26  )
27 def wrap_onspace_strict(text, width):
28  """
29  Similar to wrap_onspace, but enforces the width constraint:
30  words longer than width are split.
31  """
32  wordRegex = re.compile(r'\S{'+str(width)+r',}')
33  return wrap_onspace(wordRegex.sub(lambda m: wrap_always(m.group(),width),text),width)
34 
35 if __name__ == '__main__':
36  print wrap_always('1234567\ntrtyu43222',5)
37  print ''.join(['-']*5)+'|'
38  print wrap_onspace('1234567\ntrtyu43222',5)
39  print ''.join(['-']*5)+'|'
40  print wrap_onspace_strict('1234567\ntrtyu43222',5)
41  print ''.join(['-']*5)+'|'
def wrap_onspace_strict
Definition: wordWrappers.py:27
static std::string join(char **cmd)
Definition: RemoteFile.cc:18