CMS 3D CMS Logo

tablePrinter.py
Go to the documentation of this file.
1 from __future__ import print_function
2 from __future__ import absolute_import
3 #
4 # pretty table printer
5 # written by George Sakkis
6 # http://code.activestate.com/recipes/267662
7 #
8 import cStringIO,operator
9 from functools import reduce
10 def indent(rows,hasHeader=False,headerChar='-',delim=' | ',justify='center',
11  separateRows=False,prefix='',postfix='',wrapfunc=lambda x:x):
12  """
13  Indents a table by column.
14  - rows: A sequence of sequences of items, one sequence per row.
15  - hadHeader: True if the first row consists of the column's names.
16  - headerChar: Character to be used for the row separator line
17  (if hasHeader==True or separateRows==True).
18  - delim: The column delimiter.
19  - justify: Determines how are data justified in their column.
20  Valid values are 'left','right','center'.
21  - separateRows: True if rows are to be separated by a line of 'headerChar's.
22  - prefix: A string prepended to each printed row.
23  - postfix: A string appended to each printed row.
24  - wrapfunc: A function f(text) for wrapping text; each element in the table is first wrapped by this function.
25  """
26  #nested function
27  #closure for breaking logical rows to physical, using wrapfunc
28  def rowWrapper(row):
29  newRows=[wrapfunc(item).split('\n') for item in row]
30  #print 'newRows: ',newRows
31  #print 'map result: ',map(None,*newRows)
32  #print 'rowwrapped: ',[[substr or '' for substr in item] for item in map(None,*newRows)]
33  return [[substr or '' for substr in item] for item in map(None,*newRows)]
34  # break each logical row into one or more physical ones
35  logicalRows = [rowWrapper(row) for row in rows]
36  # columns of physical rows
37  columns = map(None,*reduce(operator.add,logicalRows))
38  # get the maximum of each column by the string length of its items
39  maxWidths = [max([len(str(item)) for item in column]) for column in columns]
40  rowSeparator = headerChar * (len(prefix) + len(postfix) + sum(maxWidths) + len(delim)*(len(maxWidths)-1))
41  # select the appropriate justify method
42  justify = {'center':str.center,'right':str.rjust,'left':str.ljust}[justify.lower()]
43  output=cStringIO.StringIO()
44  if separateRows: print(rowSeparator, file=output)
45  for physicalRows in logicalRows:
46  for row in physicalRows:
47  print(prefix+delim.join([justify(str(item),width) for (item,width) in zip(row,maxWidths)])+postfix, file=output)
48  if separateRows or hasHeader: print(rowSeparator, file=output); hasHeader=False
49  return output.getvalue()
50 
51 if __name__ == '__main__':
52  from .wordWrappers import wrap_always,wrap_onspace,wrap_onspace_strict
53  labels=('First Name','Last Name','Age','Position')
54  data="""John,Smith,24,Software Engineer
55  Mary,Brohowski,23,Sales Manager
56  Aristidis,Papageorgopoulos,28,Senior Reseacher"""
57  rows=[row.strip().split(',') for row in data.splitlines()]
58  print(rows)
59  print('without wrapping function\n')
60  print('raw input: ',[labels]+rows)
61  print(indent([labels]+rows,hasHeader=True))
62  width=10
63  for wrapper in (wrap_always,wrap_onspace,wrap_onspace_strict):
64  print('Wrapping function: %s(x,width=%d)\n'%(wrapper.__name__,width))
65  print(indent([labels]+rows,hasHeader=True,separateRows=True,prefix='| ',postfix=' |',wrapfunc=lambda x: wrapper(x,width)))
66 
67  lumidata=[\
68  ('%-*s'%(8,'run'),'%-*s'%(8,'first'),'%-*s'%(8,'last'),'%-*s'%(10,'delivered'),'%-*s'%(10,'recorded'),'%-*s'%(20,'recorded\nmypathdfdafddafd')),\
69  ['%d'%(132440),'%d'%(23),'%d'%(99),'%.2f'%(2.345),'%.2f'%(1.23),'%.2f'%(0.5678)],\
70  ['%d'%(132442),'%d'%(1),'%d'%(20),'%.2f'%(2.345),'%.2f'%(1.23),'%.2f'%(0.5678)],\
71  ['','%d'%(27),'%d'%(43),'%.2f'%(2.345),'%.2f'%(1.23),'%.2f'%(0.5678)]\
72  ]
73  lumiheader=[('%-*s'%(30,'Lumi Sections'),'%-*s'%(46,'Luminosity'))]
74  headerwidth=46
75  print(indent(lumiheader,hasHeader=True,separateRows=False,prefix='| ',postfix='',wrapfunc=lambda x: wrap_always(x,headerwidth)))
76  lumifooter=[('%-*s'%(24,'189'),'%-*s'%(10,'17.89'),'%-*s'%(10,'16.1'),'%-*s'%(20,'3.47'))]
77  width=20
78  print(indent(lumidata,hasHeader=True,separateRows=False,prefix='| ',postfix='',wrapfunc=lambda x: wrap_onspace_strict(x,width)))
79  print()
80  print(indent(lumifooter,hasHeader=False,separateRows=True,prefix=' total: ',postfix='',delim=' | ',wrapfunc=lambda x: wrap_always(x,25)))
def wrap_always(text, width)
Definition: dataformats.py:71
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
OutputIterator zip(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp)
def wrap_onspace_strict(text, width)
Definition: dataformats.py:64
#define str(s)
double split
Definition: MVATrainer.cc:139
static HepMC::HEPEVT_Wrapper wrapper
def indent(rows, hasHeader=False, headerChar='-', delim='| ', justify='center', separateRows=False, prefix='', postfix='', wrapfunc=lambda x:x)
Definition: tablePrinter.py:11