CMS 3D CMS Logo

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