prettytable 0.6.1__zip → 0.7.1__zip

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env python
2
2
  #
3
- # Copyright (c) 2009, Luke Maurits <luke@maurits.id.au>
3
+ # Copyright (c) 2009-2013, Luke Maurits <luke@maurits.id.au>
4
4
  # All rights reserved.
5
5
  # With contributions from:
6
6
  # * Chris Clark
@@ -29,17 +29,31 @@
29
29
  # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30
30
  # POSSIBILITY OF SUCH DAMAGE.
31
31
 
32
- __version__ = "0.6.1"
32
+ __version__ = "0.7.1"
33
33
 
34
- import sys
35
34
  import copy
35
+ import csv
36
36
  import random
37
+ import re
38
+ import sys
37
39
  import textwrap
40
+ import itertools
41
+ import unicodedata
38
42
 
39
43
  py3k = sys.version_info[0] >= 3
40
44
  if py3k:
41
45
  unicode = str
42
46
  basestring = str
47
+ itermap = map
48
+ iterzip = zip
49
+ uni_chr = chr
50
+ from html.parser import HTMLParser
51
+ else:
52
+ itermap = itertools.imap
53
+ iterzip = itertools.izip
54
+ uni_chr = unichr
55
+ from HTMLParser import HTMLParser
56
+
43
57
  if py3k and sys.version_info[1] >= 2:
44
58
  from html import escape
45
59
  else:
@@ -49,6 +63,7 @@ else:
49
63
  FRAME = 0
50
64
  ALL = 1
51
65
  NONE = 2
66
+ HEADER = 3
52
67
 
53
68
  # Table styles
54
69
  DEFAULT = 10
@@ -56,43 +71,34 @@ MSWORD_FRIENDLY = 11
56
71
  PLAIN_COLUMNS = 12
57
72
  RANDOM = 20
58
73
 
74
+ _re = re.compile("\033\[[0-9;]*m")
75
+
59
76
  def _get_size(text):
60
- max_width = 0
61
- max_height = 0
62
- text = _unicode(text)
63
- for line in text.split("\n"):
64
- max_height += 1
65
- if len(line) > max_width:
66
- max_width = len(line)
67
-
68
- return (max_width, max_height)
77
+ lines = text.split("\n")
78
+ height = len(lines)
79
+ width = max([_str_block_width(line) for line in lines])
80
+ return (width, height)
69
81
 
70
- def _unicode(value, encoding="UTF-8"):
71
- if not isinstance(value, basestring):
72
- value = str(value)
73
- if not isinstance(value, unicode):
74
- value = unicode(value, encoding, "replace")
75
- return value
76
-
77
82
  class PrettyTable(object):
78
83
 
79
- def __init__(self, field_names=None, encoding="UTF-8", **kwargs):
84
+ def __init__(self, field_names=None, **kwargs):
80
85
 
81
86
  """Return a new PrettyTable instance
82
87
 
83
88
  Arguments:
84
89
 
90
+ encoding - Unicode encoding scheme used to decode any encoded input
85
91
  field_names - list or tuple of field names
86
- encoding - Unicode encoding scheme to use
87
92
  fields - list or tuple of field names to include in displays
88
93
  start - index of first data row to include in output
89
94
  end - index of last data row to include in output PLUS ONE (list slice style)
90
- fields - names of fields (columns) to include
91
95
  header - print a header showing field names (True or False)
96
+ header_style - stylisation to apply to field names in header ("cap", "title", "upper", "lower" or None)
92
97
  border - print a border around the table (True or False)
93
- hrules - controls printing of horizontal rules after rows. Allowed values: FRAME, ALL, NONE
94
- int_format - controls formatting of integer data
95
- float_format - controls formatting of floating point data
98
+ hrules - controls printing of horizontal rules after rows. Allowed values: FRAME, HEADER, ALL, NONE
99
+ vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
100
+ int_format - controls formatting of integer data
101
+ float_format - controls formatting of floating point data
96
102
  padding_width - number of spaces on either side of column data (only used if left and right paddings are None)
97
103
  left_padding_width - number of spaces on left hand side of column data
98
104
  right_padding_width - number of spaces on right hand side of column data
@@ -101,57 +107,97 @@ class PrettyTable(object):
101
107
  junction_char - single character string used to draw line junctions
102
108
  sortby - name of field to sort rows by
103
109
  sort_key - sorting key function, applied to data points before sorting
110
+ valign - default valign for each row (None, "t", "m" or "b")
104
111
  reversesort - True or False to sort in descending or ascending order"""
105
112
 
106
- self.encoding = encoding
113
+ self.encoding = kwargs.get("encoding", "UTF-8")
107
114
 
108
115
  # Data
109
116
  self._field_names = []
110
117
  self._align = {}
118
+ self._valign = {}
111
119
  self._max_width = {}
112
120
  self._rows = []
113
121
  if field_names:
114
122
  self.field_names = field_names
115
123
  else:
116
124
  self._widths = []
117
- self._rows = []
118
125
 
119
126
  # Options
120
- self._options = "start end fields header border sortby reversesort sort_key attributes format hrules".split()
127
+ self._options = "start end fields header border sortby reversesort sort_key attributes format hrules vrules".split()
121
128
  self._options.extend("int_format float_format padding_width left_padding_width right_padding_width".split())
122
- self._options.extend("vertical_char horizontal_char junction_char".split())
129
+ self._options.extend("vertical_char horizontal_char junction_char header_style valign xhtml".split())
123
130
  for option in self._options:
124
131
  if option in kwargs:
125
132
  self._validate_option(option, kwargs[option])
126
133
  else:
127
134
  kwargs[option] = None
128
135
 
129
-
130
136
  self._start = kwargs["start"] or 0
131
137
  self._end = kwargs["end"] or None
132
138
  self._fields = kwargs["fields"] or None
133
139
 
134
- self._header = kwargs["header"] or True
135
- self._border = kwargs["border"] or True
140
+ if kwargs["header"] in (True, False):
141
+ self._header = kwargs["header"]
142
+ else:
143
+ self._header = True
144
+ self._header_style = kwargs["header_style"] or None
145
+ if kwargs["border"] in (True, False):
146
+ self._border = kwargs["border"]
147
+ else:
148
+ self._border = True
136
149
  self._hrules = kwargs["hrules"] or FRAME
150
+ self._vrules = kwargs["vrules"] or ALL
137
151
 
138
152
  self._sortby = kwargs["sortby"] or None
139
- self._reversesort = kwargs["reversesort"] or False
153
+ if kwargs["reversesort"] in (True, False):
154
+ self._reversesort = kwargs["reversesort"]
155
+ else:
156
+ self._reversesort = False
140
157
  self._sort_key = kwargs["sort_key"] or (lambda x: x)
141
158
 
142
- self._int_format = kwargs["float_format"] or {}
159
+ self._int_format = kwargs["int_format"] or {}
143
160
  self._float_format = kwargs["float_format"] or {}
144
161
  self._padding_width = kwargs["padding_width"] or 1
145
162
  self._left_padding_width = kwargs["left_padding_width"] or None
146
163
  self._right_padding_width = kwargs["right_padding_width"] or None
147
164
 
148
- self._vertical_char = kwargs["vertical_char"] or "|"
149
- self._horizontal_char = kwargs["horizontal_char"] or "-"
150
- self._junction_char = kwargs["junction_char"] or "+"
165
+ self._vertical_char = kwargs["vertical_char"] or self._unicode("|")
166
+ self._horizontal_char = kwargs["horizontal_char"] or self._unicode("-")
167
+ self._junction_char = kwargs["junction_char"] or self._unicode("+")
151
168
 
152
169
  self._format = kwargs["format"] or False
170
+ self._xhtml = kwargs["xhtml"] or False
153
171
  self._attributes = kwargs["attributes"] or {}
154
172
 
173
+ def _unicode(self, value):
174
+ if not isinstance(value, basestring):
175
+ value = str(value)
176
+ if not isinstance(value, unicode):
177
+ value = unicode(value, self.encoding, "strict")
178
+ return value
179
+
180
+ def _justify(self, text, width, align):
181
+ excess = width - _str_block_width(text)
182
+ if align == "l":
183
+ return text + excess * " "
184
+ elif align == "r":
185
+ return excess * " " + text
186
+ else:
187
+ if excess % 2:
188
+ # Uneven padding
189
+ # Put more space on right if text is of odd length...
190
+ if _str_block_width(text) % 2:
191
+ return (excess//2)*" " + text + (excess//2 + 1)*" "
192
+ # and more space on left if text is of even length
193
+ else:
194
+ return (excess//2 + 1)*" " + text + (excess//2)*" "
195
+ # Why distribute extra space this way? To match the behaviour of
196
+ # the inbuilt str.center() method.
197
+ else:
198
+ # Equal padding on either side
199
+ return (excess//2)*" " + text + (excess//2)*" "
200
+
155
201
  def __getattr__(self, name):
156
202
 
157
203
  if name == "rowcount":
@@ -168,20 +214,26 @@ class PrettyTable(object):
168
214
 
169
215
  def __getitem__(self, index):
170
216
 
171
- newtable = copy.deepcopy(self)
217
+ new = PrettyTable()
218
+ new.field_names = self.field_names
219
+ for attr in self._options:
220
+ setattr(new, "_"+attr, getattr(self, "_"+attr))
221
+ setattr(new, "_align", getattr(self, "_align"))
172
222
  if isinstance(index, slice):
173
- newtable._rows = self._rows[index]
223
+ for row in self._rows[index]:
224
+ new.add_row(row)
174
225
  elif isinstance(index, int):
175
- newtable._rows = [self._rows[index],]
226
+ new.add_row(self._rows[index])
176
227
  else:
177
228
  raise Exception("Index %s is invalid, must be an integer or slice" % str(index))
178
- return newtable
229
+ return new
179
230
 
180
- def __str__(self):
181
- if py3k:
182
- return self.get_string()
183
- else:
184
- return self.get_string().encode(self.encoding)
231
+ if py3k:
232
+ def __str__(self):
233
+ return self.__unicode__()
234
+ else:
235
+ def __str__(self):
236
+ return self.__unicode__().encode(self.encoding)
185
237
 
186
238
  def __unicode__(self):
187
239
  return self.get_string()
@@ -198,7 +250,9 @@ class PrettyTable(object):
198
250
  # Secondly, in the _get_options method, where keyword arguments are mixed with persistent settings
199
251
 
200
252
  def _validate_option(self, option, val):
201
- if option in ("start", "end", "padding_width", "left_padding_width", "right_padding_width", "format"):
253
+ if option in ("field_names"):
254
+ self._validate_field_names(val)
255
+ elif option in ("start", "end", "max_width", "padding_width", "left_padding_width", "right_padding_width", "format"):
202
256
  self._validate_nonnegative_int(option, val)
203
257
  elif option in ("sortby"):
204
258
  self._validate_field_name(option, val)
@@ -206,10 +260,14 @@ class PrettyTable(object):
206
260
  self._validate_function(option, val)
207
261
  elif option in ("hrules"):
208
262
  self._validate_hrules(option, val)
263
+ elif option in ("vrules"):
264
+ self._validate_vrules(option, val)
209
265
  elif option in ("fields"):
210
266
  self._validate_all_field_names(option, val)
211
- elif option in ("header", "border", "reversesort"):
267
+ elif option in ("header", "border", "reversesort", "xhtml"):
212
268
  self._validate_true_or_false(option, val)
269
+ elif option in ("header_style"):
270
+ self._validate_header_style(val)
213
271
  elif option in ("int_format"):
214
272
  self._validate_int_format(option, val)
215
273
  elif option in ("float_format"):
@@ -221,17 +279,47 @@ class PrettyTable(object):
221
279
  else:
222
280
  raise Exception("Unrecognised option: %s!" % option)
223
281
 
282
+ def _validate_field_names(self, val):
283
+ # Check for appropriate length
284
+ if self._field_names:
285
+ try:
286
+ assert len(val) == len(self._field_names)
287
+ except AssertionError:
288
+ raise Exception("Field name list has incorrect number of values, (actual) %d!=%d (expected)" % (len(val), len(self._field_names)))
289
+ if self._rows:
290
+ try:
291
+ assert len(val) == len(self._rows[0])
292
+ except AssertionError:
293
+ raise Exception("Field name list has incorrect number of values, (actual) %d!=%d (expected)" % (len(val), len(self._rows[0])))
294
+ # Check for uniqueness
295
+ try:
296
+ assert len(val) == len(set(val))
297
+ except AssertionError:
298
+ raise Exception("Field names must be unique!")
299
+
300
+ def _validate_header_style(self, val):
301
+ try:
302
+ assert val in ("cap", "title", "upper", "lower", None)
303
+ except AssertionError:
304
+ raise Exception("Invalid header style, use cap, title, upper, lower or None!")
305
+
224
306
  def _validate_align(self, val):
225
307
  try:
226
308
  assert val in ["l","c","r"]
227
309
  except AssertionError:
228
310
  raise Exception("Alignment %s is invalid, use l, c or r!" % val)
229
311
 
312
+ def _validate_valign(self, val):
313
+ try:
314
+ assert val in ["t","m","b",None]
315
+ except AssertionError:
316
+ raise Exception("Alignment %s is invalid, use t, m, b or None!" % val)
317
+
230
318
  def _validate_nonnegative_int(self, name, val):
231
319
  try:
232
320
  assert int(val) >= 0
233
321
  except AssertionError:
234
- raise Exception("Invalid value for %s: %s!" % (name, _unicode(val)))
322
+ raise Exception("Invalid value for %s: %s!" % (name, self._unicode(val)))
235
323
 
236
324
  def _validate_true_or_false(self, name, val):
237
325
  try:
@@ -268,14 +356,20 @@ class PrettyTable(object):
268
356
  raise Exception("Invalid value for %s! Must be a function." % name)
269
357
 
270
358
  def _validate_hrules(self, name, val):
359
+ try:
360
+ assert val in (ALL, FRAME, HEADER, NONE)
361
+ except AssertionError:
362
+ raise Exception("Invalid value for %s! Must be ALL, FRAME, HEADER or NONE." % name)
363
+
364
+ def _validate_vrules(self, name, val):
271
365
  try:
272
366
  assert val in (ALL, FRAME, NONE)
273
367
  except AssertionError:
274
- raise Exception("Invalid value for %s! Must be ALL, FRAME or NONE." % name)
368
+ raise Exception("Invalid value for %s! Must be ALL, FRAME, or NONE." % name)
275
369
 
276
370
  def _validate_field_name(self, name, val):
277
371
  try:
278
- assert val in self._field_names
372
+ assert (val in self._field_names) or (val is None)
279
373
  except AssertionError:
280
374
  raise Exception("Invalid field name: %s!" % val)
281
375
 
@@ -288,7 +382,7 @@ class PrettyTable(object):
288
382
 
289
383
  def _validate_single_char(self, name, val):
290
384
  try:
291
- assert len(_unicode(val)) == 1
385
+ assert _str_block_width(val) == 1
292
386
  except AssertionError:
293
387
  raise Exception("Invalid value for %s! Must be a string of length 1." % name)
294
388
 
@@ -310,6 +404,8 @@ class PrettyTable(object):
310
404
 
311
405
  fields - list or tuple of field names"""
312
406
  def _set_field_names(self, val):
407
+ val = [self._unicode(x) for x in val]
408
+ self._validate_option("field_names", val)
313
409
  if self._field_names:
314
410
  old_names = self._field_names[:]
315
411
  self._field_names = val
@@ -317,10 +413,20 @@ class PrettyTable(object):
317
413
  for old_name, new_name in zip(old_names, val):
318
414
  self._align[new_name] = self._align[old_name]
319
415
  for old_name in old_names:
320
- self._align.pop(old_name)
416
+ if old_name not in self._align:
417
+ self._align.pop(old_name)
321
418
  else:
322
419
  for field in self._field_names:
323
420
  self._align[field] = "c"
421
+ if self._valign and old_names:
422
+ for old_name, new_name in zip(old_names, val):
423
+ self._valign[new_name] = self._valign[old_name]
424
+ for old_name in old_names:
425
+ if old_name not in self._valign:
426
+ self._valign.pop(old_name)
427
+ else:
428
+ for field in self._field_names:
429
+ self._valign[field] = "t"
324
430
  field_names = property(_get_field_names, _set_field_names)
325
431
 
326
432
  def _get_align(self):
@@ -331,14 +437,34 @@ class PrettyTable(object):
331
437
  self._align[field] = val
332
438
  align = property(_get_align, _set_align)
333
439
 
440
+ def _get_valign(self):
441
+ return self._valign
442
+ def _set_valign(self, val):
443
+ self._validate_valign(val)
444
+ for field in self._field_names:
445
+ self._valign[field] = val
446
+ valign = property(_get_valign, _set_valign)
447
+
334
448
  def _get_max_width(self):
335
449
  return self._max_width
336
450
  def _set_max_width(self, val):
337
- self._validate_nonnegativeint(val)
451
+ self._validate_option("max_width", val)
338
452
  for field in self._field_names:
339
453
  self._max_width[field] = val
340
454
  max_width = property(_get_max_width, _set_max_width)
341
455
 
456
+ def _get_fields(self):
457
+ """List or tuple of field names to include in displays
458
+
459
+ Arguments:
460
+
461
+ fields - list or tuple of field names to include in displays"""
462
+ return self._fields
463
+ def _set_fields(self, val):
464
+ self._validate_option("fields", val)
465
+ self._fields = val
466
+ fields = property(_get_fields, _set_fields)
467
+
342
468
  def _get_start(self):
343
469
  """Start index of the range of rows to print
344
470
 
@@ -412,6 +538,18 @@ class PrettyTable(object):
412
538
  self._header = val
413
539
  header = property(_get_header, _set_header)
414
540
 
541
+ def _get_header_style(self):
542
+ """Controls stylisation applied to field names in header
543
+
544
+ Arguments:
545
+
546
+ header_style - stylisation to apply to field names in header ("cap", "title", "upper", "lower" or None)"""
547
+ return self._header_style
548
+ def _set_header_style(self, val):
549
+ self._validate_header_style(val)
550
+ self._header_style = val
551
+ header_style = property(_get_header_style, _set_header_style)
552
+
415
553
  def _get_border(self):
416
554
  """Controls printing of border around table
417
555
 
@@ -429,13 +567,25 @@ class PrettyTable(object):
429
567
 
430
568
  Arguments:
431
569
 
432
- hrules - horizontal rules style. Allowed values: FRAME, ALL, NONE"""
570
+ hrules - horizontal rules style. Allowed values: FRAME, ALL, HEADER, NONE"""
433
571
  return self._hrules
434
572
  def _set_hrules(self, val):
435
573
  self._validate_option("hrules", val)
436
574
  self._hrules = val
437
575
  hrules = property(_get_hrules, _set_hrules)
438
576
 
577
+ def _get_vrules(self):
578
+ """Controls printing of vertical rules between columns
579
+
580
+ Arguments:
581
+
582
+ vrules - vertical rules style. Allowed values: FRAME, ALL, NONE"""
583
+ return self._vrules
584
+ def _set_vrules(self, val):
585
+ self._validate_option("vrules", val)
586
+ self._vrules = val
587
+ vrules = property(_get_vrules, _set_vrules)
588
+
439
589
  def _get_int_format(self):
440
590
  """Controls formatting of integer data
441
591
  Arguments:
@@ -443,7 +593,7 @@ class PrettyTable(object):
443
593
  int_format - integer format string"""
444
594
  return self._int_format
445
595
  def _set_int_format(self, val):
446
- self._validate_option("int_format", val)
596
+ # self._validate_option("int_format", val)
447
597
  for field in self._field_names:
448
598
  self._int_format[field] = val
449
599
  int_format = property(_get_int_format, _set_int_format)
@@ -455,7 +605,7 @@ class PrettyTable(object):
455
605
  float_format - floating point format string"""
456
606
  return self._float_format
457
607
  def _set_float_format(self, val):
458
- self._validate_option("float_format", val)
608
+ # self._validate_option("float_format", val)
459
609
  for field in self._field_names:
460
610
  self._float_format[field] = val
461
611
  float_format = property(_get_float_format, _set_float_format)
@@ -504,6 +654,7 @@ class PrettyTable(object):
504
654
  vertical_char - single character string used to draw vertical lines"""
505
655
  return self._vertical_char
506
656
  def _set_vertical_char(self, val):
657
+ val = self._unicode(val)
507
658
  self._validate_option("vertical_char", val)
508
659
  self._vertical_char = val
509
660
  vertical_char = property(_get_vertical_char, _set_vertical_char)
@@ -516,6 +667,7 @@ class PrettyTable(object):
516
667
  horizontal_char - single character string used to draw horizontal lines"""
517
668
  return self._horizontal_char
518
669
  def _set_horizontal_char(self, val):
670
+ val = self._unicode(val)
519
671
  self._validate_option("horizontal_char", val)
520
672
  self._horizontal_char = val
521
673
  horizontal_char = property(_get_horizontal_char, _set_horizontal_char)
@@ -528,6 +680,7 @@ class PrettyTable(object):
528
680
  junction_char - single character string used to draw line junctions"""
529
681
  return self._junction_char
530
682
  def _set_junction_char(self, val):
683
+ val = self._unicode(val)
531
684
  self._validate_option("vertical_char", val)
532
685
  self._junction_char = val
533
686
  junction_char = property(_get_junction_char, _set_junction_char)
@@ -552,7 +705,7 @@ class PrettyTable(object):
552
705
  attributes - dictionary of attributes"""
553
706
  return self._attributes
554
707
  def _set_attributes(self, val):
555
- self.validate_option("attributes", val)
708
+ self._validate_option("attributes", val)
556
709
  self._attributes = val
557
710
  attributes = property(_get_attributes, _set_attributes)
558
711
 
@@ -593,6 +746,7 @@ class PrettyTable(object):
593
746
  self.header = True
594
747
  self.border = True
595
748
  self._hrules = FRAME
749
+ self._vrules = ALL
596
750
  self.padding_width = 1
597
751
  self.left_padding_width = 1
598
752
  self.right_padding_width = 1
@@ -623,7 +777,8 @@ class PrettyTable(object):
623
777
  # Just for fun!
624
778
  self.header = random.choice((True, False))
625
779
  self.border = random.choice((True, False))
626
- self._hrules = random.choice((ALL, FRAME, NONE))
780
+ self._hrules = random.choice((ALL, FRAME, HEADER, NONE))
781
+ self._vrules = random.choice((ALL, FRAME, NONE))
627
782
  self.left_padding_width = random.randint(0,5)
628
783
  self.right_padding_width = random.randint(0,5)
629
784
  self.vertical_char = random.choice("~!@#$%^&*()_+|-=\{}[];':\",./;<>?")
@@ -645,6 +800,8 @@ class PrettyTable(object):
645
800
 
646
801
  if self._field_names and len(row) != len(self._field_names):
647
802
  raise Exception("Row has incorrect number of values, (actual) %d!=%d (expected)" %(len(row),len(self._field_names)))
803
+ if not self._field_names:
804
+ self.field_names = [("Field %d" % (n+1)) for n in range(0,len(row))]
648
805
  self._rows.append(list(row))
649
806
 
650
807
  def del_row(self, row_index):
@@ -659,7 +816,7 @@ class PrettyTable(object):
659
816
  raise Exception("Cant delete row at index %d, table only has %d rows!" % (row_index, len(self._rows)))
660
817
  del self._rows[row_index]
661
818
 
662
- def add_column(self, fieldname, column, align="c"):
819
+ def add_column(self, fieldname, column, align="c", valign="t"):
663
820
 
664
821
  """Add a column to the table.
665
822
 
@@ -668,12 +825,15 @@ class PrettyTable(object):
668
825
  fieldname - name of the field to contain the new column of data
669
826
  column - column of data, should be a list with as many elements as the
670
827
  table has rows
671
- align - desired alignment for this column - "l" for left, "c" for centre and "r" for right"""
828
+ align - desired alignment for this column - "l" for left, "c" for centre and "r" for right
829
+ valign - desired vertical alignment for new columns - "t" for top, "m" for middle and "b" for bottom"""
672
830
 
673
831
  if len(self._rows) in (0, len(column)):
674
832
  self._validate_align(align)
833
+ self._validate_valign(valign)
675
834
  self._field_names.append(fieldname)
676
835
  self._align[fieldname] = align
836
+ self._valign[fieldname] = valign
677
837
  for i in range(0, len(column)):
678
838
  if len(self._rows) < i+1:
679
839
  self._rows.append([])
@@ -708,10 +868,10 @@ class PrettyTable(object):
708
868
 
709
869
  def _format_value(self, field, value):
710
870
  if isinstance(value, int) and field in self._int_format:
711
- value = ("%%%sd" % self._int_format[field]) % value
871
+ value = self._unicode(("%%%sd" % self._int_format[field]) % value)
712
872
  elif isinstance(value, float) and field in self._float_format:
713
- value = ("%%%sf" % self._float_format[field]) % value
714
- return value
873
+ value = self._unicode(("%%%sf" % self._float_format[field]) % value)
874
+ return self._unicode(value)
715
875
 
716
876
  def _compute_widths(self, rows, options):
717
877
  if options["header"]:
@@ -720,8 +880,11 @@ class PrettyTable(object):
720
880
  widths = len(self.field_names) * [0]
721
881
  for row in rows:
722
882
  for index, value in enumerate(row):
723
- value = self._format_value(self.field_names[index], value)
724
- widths[index] = max(widths[index], _get_size(_unicode(value))[0])
883
+ fieldname = self.field_names[index]
884
+ if fieldname in self.max_width:
885
+ widths[index] = max(widths[index], min(_get_size(value)[0], self.max_width[fieldname]))
886
+ else:
887
+ widths[index] = max(widths[index], _get_size(value)[0])
725
888
  self._widths = widths
726
889
 
727
890
  def _get_padding_widths(self, options):
@@ -743,7 +906,7 @@ class PrettyTable(object):
743
906
 
744
907
  options - dictionary of option settings."""
745
908
 
746
- # Make a copy of only those rows in the slice range
909
+ # Make a copy of only those rows in the slice range
747
910
  rows = copy.deepcopy(self._rows[options["start"]:options["end"]])
748
911
  # Sort if necessary
749
912
  if options["sortby"]:
@@ -755,7 +918,13 @@ class PrettyTable(object):
755
918
  # Undecorate
756
919
  rows = [row[1:] for row in rows]
757
920
  return rows
758
-
921
+
922
+ def _format_row(self, row, options):
923
+ return [self._format_value(field, value) for (field, value) in zip(self._field_names, row)]
924
+
925
+ def _format_rows(self, rows, options):
926
+ return [self._format_row(row, options) for row in rows]
927
+
759
928
  ##############################
760
929
  # PLAIN TEXT STRING METHODS #
761
930
  ##############################
@@ -771,9 +940,10 @@ class PrettyTable(object):
771
940
  fields - names of fields (columns) to include
772
941
  header - print a header showing field names (True or False)
773
942
  border - print a border around the table (True or False)
774
- hrules - controls printing of horizontal rules after rows. Allowed values: FRAME, ALL, NONE
775
- int_format - controls formatting of integer data
776
- float_format - controls formatting of floating point data
943
+ hrules - controls printing of horizontal rules after rows. Allowed values: ALL, FRAME, HEADER, NONE
944
+ vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
945
+ int_format - controls formatting of integer data
946
+ float_format - controls formatting of floating point data
777
947
  padding_width - number of spaces on either side of column data (only used if left and right paddings are None)
778
948
  left_padding_width - number of spaces on left hand side of column data
779
949
  right_padding_width - number of spaces on right hand side of column data
@@ -786,51 +956,58 @@ class PrettyTable(object):
786
956
 
787
957
  options = self._get_options(kwargs)
788
958
 
789
- bits = []
959
+ lines = []
790
960
 
791
961
  # Don't think too hard about an empty table
962
+ # Is this the desired behaviour? Maybe we should still print the header?
792
963
  if self.rowcount == 0:
793
964
  return ""
794
965
 
966
+ # Get the rows we need to print, taking into account slicing, sorting, etc.
795
967
  rows = self._get_rows(options)
796
- self._compute_widths(rows, options)
797
968
 
798
- # Build rows
799
- # (for now, this is done before building headers etc. because rowbits.append
800
- # contains width-adjusting voodoo which has to be done first. This is ugly
801
- # and Wrong and will change soon)
802
- rowbits = []
803
- for row in rows:
804
- rowbits.append(self._stringify_row(row, options))
969
+ # Turn all data in all rows into Unicode, formatted as desired
970
+ formatted_rows = self._format_rows(rows, options)
805
971
 
972
+ # Compute column widths
973
+ self._compute_widths(formatted_rows, options)
806
974
 
807
975
  # Add header or top of border
976
+ self._hrule = self._stringify_hrule(options)
808
977
  if options["header"]:
809
- bits.append(self._stringify_header(options))
810
- elif options["border"] and options["hrules"] != NONE:
811
- bits.append(self._hrule)
978
+ lines.append(self._stringify_header(options))
979
+ elif options["border"] and options["hrules"] in (ALL, FRAME):
980
+ lines.append(self._hrule)
812
981
 
813
982
  # Add rows
814
- bits.extend(rowbits)
983
+ for row in formatted_rows:
984
+ lines.append(self._stringify_row(row, options))
815
985
 
816
986
  # Add bottom of border
817
- if options["border"] and not options["hrules"]:
818
- bits.append(self._hrule)
987
+ if options["border"] and options["hrules"] == FRAME:
988
+ lines.append(self._hrule)
819
989
 
820
- string = "\n".join(bits)
821
- self._nonunicode = string
822
- return _unicode(string)
990
+ return self._unicode("\n").join(lines)
823
991
 
824
992
  def _stringify_hrule(self, options):
825
993
 
826
994
  if not options["border"]:
827
995
  return ""
828
996
  lpad, rpad = self._get_padding_widths(options)
829
- bits = [options["junction_char"]]
997
+ if options['vrules'] in (ALL, FRAME):
998
+ bits = [options["junction_char"]]
999
+ else:
1000
+ bits = [options["horizontal_char"]]
830
1001
  for field, width in zip(self._field_names, self._widths):
831
1002
  if options["fields"] and field not in options["fields"]:
832
1003
  continue
833
1004
  bits.append((width+lpad+rpad)*options["horizontal_char"])
1005
+ if options['vrules'] == ALL:
1006
+ bits.append(options["junction_char"])
1007
+ else:
1008
+ bits.append(options["horizontal_char"])
1009
+ if options["vrules"] == FRAME:
1010
+ bits.pop()
834
1011
  bits.append(options["junction_char"])
835
1012
  return "".join(bits)
836
1013
 
@@ -839,54 +1016,56 @@ class PrettyTable(object):
839
1016
  bits = []
840
1017
  lpad, rpad = self._get_padding_widths(options)
841
1018
  if options["border"]:
842
- if options["hrules"] != NONE:
1019
+ if options["hrules"] in (ALL, FRAME):
843
1020
  bits.append(self._hrule)
844
1021
  bits.append("\n")
845
- bits.append(options["vertical_char"])
1022
+ if options["vrules"] in (ALL, FRAME):
1023
+ bits.append(options["vertical_char"])
1024
+ else:
1025
+ bits.append(" ")
846
1026
  for field, width, in zip(self._field_names, self._widths):
847
1027
  if options["fields"] and field not in options["fields"]:
848
1028
  continue
849
- if self._align[field] == "l":
850
- bits.append(" " * lpad + _unicode(field).ljust(width) + " " * rpad)
851
- elif self._align[field] == "r":
852
- bits.append(" " * lpad + _unicode(field).rjust(width) + " " * rpad)
1029
+ if self._header_style == "cap":
1030
+ fieldname = field.capitalize()
1031
+ elif self._header_style == "title":
1032
+ fieldname = field.title()
1033
+ elif self._header_style == "upper":
1034
+ fieldname = field.upper()
1035
+ elif self._header_style == "lower":
1036
+ fieldname = field.lower()
853
1037
  else:
854
- bits.append(" " * lpad + _unicode(field).center(width) + " " * rpad)
1038
+ fieldname = field
1039
+ bits.append(" " * lpad + self._justify(fieldname, width, self._align[field]) + " " * rpad)
855
1040
  if options["border"]:
856
- bits.append(options["vertical_char"])
1041
+ if options["vrules"] == ALL:
1042
+ bits.append(options["vertical_char"])
1043
+ else:
1044
+ bits.append(" ")
1045
+ # If vrules is FRAME, then we just appended a space at the end
1046
+ # of the last field, when we really want a vertical character
1047
+ if options["border"] and options["vrules"] == FRAME:
1048
+ bits.pop()
1049
+ bits.append(options["vertical_char"])
857
1050
  if options["border"] and options["hrules"] != NONE:
858
1051
  bits.append("\n")
859
1052
  bits.append(self._hrule)
860
1053
  return "".join(bits)
861
1054
 
862
1055
  def _stringify_row(self, row, options):
863
-
864
- for index, value in enumerate(row):
865
- row[index] = self._format_value(self.field_names[index], value)
866
-
1056
+
867
1057
  for index, field, value, width, in zip(range(0,len(row)), self._field_names, row, self._widths):
868
1058
  # Enforce max widths
869
- max_width = self._max_width.get(field, 0)
870
- lines = _unicode(value).split("\n")
1059
+ lines = value.split("\n")
871
1060
  new_lines = []
872
1061
  for line in lines:
873
- if max_width and len(line) > max_width:
874
- line = textwrap.fill(line, max_width)
1062
+ if _str_block_width(line) > width:
1063
+ line = textwrap.fill(line, width)
875
1064
  new_lines.append(line)
876
1065
  lines = new_lines
877
1066
  value = "\n".join(lines)
878
1067
  row[index] = value
879
1068
 
880
- #old_widths = self._widths[:]
881
-
882
- for index, field in enumerate(self._field_names):
883
- namewidth = len(field)
884
- datawidth = min(self._widths[index], self._max_width.get(field, self._widths[index]))
885
- if options["header"]:
886
- self._widths[index] = max(namewidth, datawidth)
887
- else:
888
- self._widths[index] = datawidth
889
-
890
1069
  row_height = 0
891
1070
  for c in row:
892
1071
  h = _get_size(c)[1]
@@ -898,31 +1077,43 @@ class PrettyTable(object):
898
1077
  for y in range(0, row_height):
899
1078
  bits.append([])
900
1079
  if options["border"]:
901
- bits[y].append(self.vertical_char)
1080
+ if options["vrules"] in (ALL, FRAME):
1081
+ bits[y].append(self.vertical_char)
1082
+ else:
1083
+ bits[y].append(" ")
902
1084
 
903
1085
  for field, value, width, in zip(self._field_names, row, self._widths):
904
1086
 
905
- lines = _unicode(value).split("\n")
906
- if len(lines) < row_height:
907
- lines = lines + ([""] * (row_height-len(lines)))
1087
+ valign = self._valign[field]
1088
+ lines = value.split("\n")
1089
+ dHeight = row_height - len(lines)
1090
+ if dHeight:
1091
+ if valign == "m":
1092
+ lines = [""] * int(dHeight / 2) + lines + [""] * (dHeight - int(dHeight / 2))
1093
+ elif valign == "b":
1094
+ lines = [""] * dHeight + lines
1095
+ else:
1096
+ lines = lines + [""] * dHeight
908
1097
 
909
1098
  y = 0
910
1099
  for l in lines:
911
1100
  if options["fields"] and field not in options["fields"]:
912
1101
  continue
913
1102
 
914
- if self._align[field] == "l":
915
- bits[y].append(" " * lpad + _unicode(l).ljust(width) + " " * rpad)
916
- elif self._align[field] == "r":
917
- bits[y].append(" " * lpad + _unicode(l).rjust(width) + " " * rpad)
918
- else:
919
- bits[y].append(" " * lpad + _unicode(l).center(width) + " " * rpad)
1103
+ bits[y].append(" " * lpad + self._justify(l, width, self._align[field]) + " " * rpad)
920
1104
  if options["border"]:
921
- bits[y].append(self.vertical_char)
922
-
1105
+ if options["vrules"] == ALL:
1106
+ bits[y].append(self.vertical_char)
1107
+ else:
1108
+ bits[y].append(" ")
923
1109
  y += 1
924
1110
 
925
- self._hrule = self._stringify_hrule(options)
1111
+ # If vrules is FRAME, then we just appended a space at the end
1112
+ # of the last field, when we really want a vertical character
1113
+ for y in range(0, row_height):
1114
+ if options["border"] and options["vrules"] == FRAME:
1115
+ bits[y].pop()
1116
+ bits[y].append(options["vertical_char"])
926
1117
 
927
1118
  if options["border"] and options["hrules"]== ALL:
928
1119
  bits[row_height-1].append("\n")
@@ -931,8 +1122,6 @@ class PrettyTable(object):
931
1122
  for y in range(0, row_height):
932
1123
  bits[y] = "".join(bits[y])
933
1124
 
934
- #self._widths = old_widths
935
-
936
1125
  return "\n".join(bits)
937
1126
 
938
1127
  ##############################
@@ -950,15 +1139,17 @@ class PrettyTable(object):
950
1139
  fields - names of fields (columns) to include
951
1140
  header - print a header showing field names (True or False)
952
1141
  border - print a border around the table (True or False)
953
- hrules - controls printing of horizontal rules after rows. Allowed values: FRAME, ALL, NONE
954
- int_format - controls formatting of integer data
955
- float_format - controls formatting of floating point data
1142
+ hrules - controls printing of horizontal rules after rows. Allowed values: ALL, FRAME, HEADER, NONE
1143
+ vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
1144
+ int_format - controls formatting of integer data
1145
+ float_format - controls formatting of floating point data
956
1146
  padding_width - number of spaces on either side of column data (only used if left and right paddings are None)
957
1147
  left_padding_width - number of spaces on left hand side of column data
958
1148
  right_padding_width - number of spaces on right hand side of column data
959
1149
  sortby - name of field to sort rows by
960
1150
  sort_key - sorting key function, applied to data points before sorting
961
- attributes - dictionary of name/value pairs to include as HTML attributes in the <table> tag"""
1151
+ attributes - dictionary of name/value pairs to include as HTML attributes in the <table> tag
1152
+ xhtml - print <br/> tags if True, <br> tags if false"""
962
1153
 
963
1154
  options = self._get_options(kwargs)
964
1155
 
@@ -967,97 +1158,282 @@ class PrettyTable(object):
967
1158
  else:
968
1159
  string = self._get_simple_html_string(options)
969
1160
 
970
- self._nonunicode = string
971
- return _unicode(string)
1161
+ return string
972
1162
 
973
1163
  def _get_simple_html_string(self, options):
974
1164
 
975
- bits = []
976
- # Slow but works
977
- table_tag = '<table'
978
- if options["border"]:
979
- table_tag += ' border="1"'
1165
+ lines = []
1166
+ if options["xhtml"]:
1167
+ linebreak = "<br/>"
1168
+ else:
1169
+ linebreak = "<br>"
1170
+
1171
+ open_tag = []
1172
+ open_tag.append("<table")
980
1173
  if options["attributes"]:
981
1174
  for attr_name in options["attributes"]:
982
- table_tag += ' %s="%s"' % (attr_name, options["attributes"][attr_name])
983
- table_tag += '>'
984
- bits.append(table_tag)
1175
+ open_tag.append(" %s=\"%s\"" % (attr_name, options["attributes"][attr_name]))
1176
+ open_tag.append(">")
1177
+ lines.append("".join(open_tag))
985
1178
 
986
1179
  # Headers
987
1180
  if options["header"]:
988
- bits.append(" <tr>")
1181
+ lines.append(" <tr>")
989
1182
  for field in self._field_names:
990
1183
  if options["fields"] and field not in options["fields"]:
991
1184
  continue
992
- bits.append(" <th>%s</th>" % escape(_unicode(field)).replace("\n", "<br />"))
993
- bits.append(" </tr>")
1185
+ lines.append(" <th>%s</th>" % escape(field).replace("\n", linebreak))
1186
+ lines.append(" </tr>")
994
1187
 
995
1188
  # Data
996
1189
  rows = self._get_rows(options)
997
- for row in rows:
998
- bits.append(" <tr>")
1190
+ formatted_rows = self._format_rows(rows, options)
1191
+ for row in formatted_rows:
1192
+ lines.append(" <tr>")
999
1193
  for field, datum in zip(self._field_names, row):
1000
1194
  if options["fields"] and field not in options["fields"]:
1001
1195
  continue
1002
- bits.append(" <td>%s</td>" % escape(_unicode(datum)).replace("\n", "<br />"))
1003
- bits.append(" </tr>")
1196
+ lines.append(" <td>%s</td>" % escape(datum).replace("\n", linebreak))
1197
+ lines.append(" </tr>")
1004
1198
 
1005
- bits.append("</table>")
1006
- string = "\n".join(bits)
1199
+ lines.append("</table>")
1007
1200
 
1008
- self._nonunicode = string
1009
- return _unicode(string)
1201
+ return self._unicode("\n").join(lines)
1010
1202
 
1011
1203
  def _get_formatted_html_string(self, options):
1012
1204
 
1013
- bits = []
1205
+ lines = []
1014
1206
  lpad, rpad = self._get_padding_widths(options)
1015
- # Slow but works
1016
- table_tag = '<table'
1207
+ if options["xhtml"]:
1208
+ linebreak = "<br/>"
1209
+ else:
1210
+ linebreak = "<br>"
1211
+
1212
+ open_tag = []
1213
+ open_tag.append("<table")
1017
1214
  if options["border"]:
1018
- table_tag += ' border="1"'
1019
- if options["hrules"] == NONE:
1020
- table_tag += ' frame="vsides" rules="cols"'
1215
+ if options["hrules"] == ALL and options["vrules"] == ALL:
1216
+ open_tag.append(" frame=\"box\" rules=\"all\"")
1217
+ elif options["hrules"] == FRAME and options["vrules"] == FRAME:
1218
+ open_tag.append(" frame=\"box\"")
1219
+ elif options["hrules"] == FRAME and options["vrules"] == ALL:
1220
+ open_tag.append(" frame=\"box\" rules=\"cols\"")
1221
+ elif options["hrules"] == FRAME:
1222
+ open_tag.append(" frame=\"hsides\"")
1223
+ elif options["hrules"] == ALL:
1224
+ open_tag.append(" frame=\"hsides\" rules=\"rows\"")
1225
+ elif options["vrules"] == FRAME:
1226
+ open_tag.append(" frame=\"vsides\"")
1227
+ elif options["vrules"] == ALL:
1228
+ open_tag.append(" frame=\"vsides\" rules=\"cols\"")
1021
1229
  if options["attributes"]:
1022
1230
  for attr_name in options["attributes"]:
1023
- table_tag += ' %s="%s"' % (attr_name, options["attributes"][attr_name])
1024
- table_tag += '>'
1025
- bits.append(table_tag)
1231
+ open_tag.append(" %s=\"%s\"" % (attr_name, options["attributes"][attr_name]))
1232
+ open_tag.append(">")
1233
+ lines.append("".join(open_tag))
1234
+
1026
1235
  # Headers
1027
1236
  if options["header"]:
1028
- bits.append(" <tr>")
1237
+ lines.append(" <tr>")
1029
1238
  for field in self._field_names:
1030
1239
  if options["fields"] and field not in options["fields"]:
1031
1240
  continue
1032
- bits.append(" <th style=\"padding-left: %dem; padding-right: %dem; text-align: center\">%s</th>" % (lpad, rpad, escape(_unicode(field)).replace("\n", "<br />")))
1033
- bits.append(" </tr>")
1241
+ lines.append(" <th style=\"padding-left: %dem; padding-right: %dem; text-align: center\">%s</th>" % (lpad, rpad, escape(field).replace("\n", linebreak)))
1242
+ lines.append(" </tr>")
1243
+
1034
1244
  # Data
1035
1245
  rows = self._get_rows(options)
1036
- for row in self._rows:
1037
- bits.append(" <tr>")
1038
- for field, datum in zip(self._field_names, row):
1246
+ formatted_rows = self._format_rows(rows, options)
1247
+ aligns = []
1248
+ valigns = []
1249
+ for field in self._field_names:
1250
+ aligns.append({ "l" : "left", "r" : "right", "c" : "center" }[self._align[field]])
1251
+ valigns.append({"t" : "top", "m" : "middle", "b" : "bottom"}[self._valign[field]])
1252
+ for row in formatted_rows:
1253
+ lines.append(" <tr>")
1254
+ for field, datum, align, valign in zip(self._field_names, row, aligns, valigns):
1039
1255
  if options["fields"] and field not in options["fields"]:
1040
1256
  continue
1041
- if self._align[field] == "l":
1042
- bits.append(" <td style=\"padding-left: %dem; padding-right: %dem; text-align: left\">%s</td>" % (lpad, rpad, escape(_unicode(datum)).replace("\n", "<br />")))
1043
- elif self._align[field] == "r":
1044
- bits.append(" <td style=\"padding-left: %dem; padding-right: %dem; text-align: right\">%s</td>" % (lpad, rpad, escape(_unicode(datum)).replace("\n", "<br />")))
1045
- else:
1046
- bits.append(" <td style=\"padding-left: %dem; padding-right: %dem; text-align: center\">%s</td>" % (lpad, rpad, escape(_unicode(datum)).replace("\n", "<br />")))
1047
- bits.append(" </tr>")
1048
- bits.append("</table>")
1049
- string = "\n".join(bits)
1050
-
1051
- self._nonunicode = string
1052
- return _unicode(string)
1257
+ lines.append(" <td style=\"padding-left: %dem; padding-right: %dem; text-align: %s; vertical-align: %s\">%s</td>" % (lpad, rpad, align, valign, escape(datum).replace("\n", linebreak)))
1258
+ lines.append(" </tr>")
1259
+ lines.append("</table>")
1260
+
1261
+ return self._unicode("\n").join(lines)
1262
+
1263
+ ##############################
1264
+ # UNICODE WIDTH FUNCTIONS #
1265
+ ##############################
1266
+
1267
+ def _char_block_width(char):
1268
+ # Basic Latin, which is probably the most common case
1269
+ #if char in xrange(0x0021, 0x007e):
1270
+ #if char >= 0x0021 and char <= 0x007e:
1271
+ if 0x0021 <= char <= 0x007e:
1272
+ return 1
1273
+ # Chinese, Japanese, Korean (common)
1274
+ if 0x4e00 <= char <= 0x9fff:
1275
+ return 2
1276
+ # Hangul
1277
+ if 0xac00 <= char <= 0xd7af:
1278
+ return 2
1279
+ # Combining?
1280
+ if unicodedata.combining(uni_chr(char)):
1281
+ return 0
1282
+ # Hiragana and Katakana
1283
+ if 0x3040 <= char <= 0x309f or 0x30a0 <= char <= 0x30ff:
1284
+ return 2
1285
+ # Full-width Latin characters
1286
+ if 0xff01 <= char <= 0xff60:
1287
+ return 2
1288
+ # CJK punctuation
1289
+ if 0x3000 <= char <= 0x303e:
1290
+ return 2
1291
+ # Backspace and delete
1292
+ if char in (0x0008, 0x007f):
1293
+ return -1
1294
+ # Other control characters
1295
+ elif char in (0x0000, 0x001f):
1296
+ return 0
1297
+ # Take a guess
1298
+ return 1
1299
+
1300
+ def _str_block_width(val):
1301
+
1302
+ return sum(itermap(_char_block_width, itermap(ord, _re.sub("", val))))
1303
+
1304
+ ##############################
1305
+ # TABLE FACTORIES #
1306
+ ##############################
1307
+
1308
+ def from_csv(fp, field_names = None, **kwargs):
1309
+
1310
+ dialect = csv.Sniffer().sniff(fp.read(1024))
1311
+ fp.seek(0)
1312
+ reader = csv.reader(fp, dialect)
1313
+
1314
+ table = PrettyTable(**kwargs)
1315
+ if field_names:
1316
+ table.field_names = field_names
1317
+ else:
1318
+ if py3k:
1319
+ table.field_names = [x.strip() for x in next(reader)]
1320
+ else:
1321
+ table.field_names = [x.strip() for x in reader.next()]
1322
+
1323
+ for row in reader:
1324
+ table.add_row([x.strip() for x in row])
1325
+
1326
+ return table
1327
+
1328
+ def from_db_cursor(cursor, **kwargs):
1329
+
1330
+ if cursor.description:
1331
+ table = PrettyTable(**kwargs)
1332
+ table.field_names = [col[0] for col in cursor.description]
1333
+ for row in cursor.fetchall():
1334
+ table.add_row(row)
1335
+ return table
1336
+
1337
+ class TableHandler(HTMLParser):
1338
+
1339
+ def __init__(self, **kwargs):
1340
+ HTMLParser.__init__(self)
1341
+ self.kwargs = kwargs
1342
+ self.tables = []
1343
+ self.last_row = []
1344
+ self.rows = []
1345
+ self.max_row_width = 0
1346
+ self.active = None
1347
+ self.last_content = ""
1348
+ self.is_last_row_header = False
1349
+
1350
+ def handle_starttag(self,tag, attrs):
1351
+ self.active = tag
1352
+ if tag == "th":
1353
+ self.is_last_row_header = True
1354
+
1355
+ def handle_endtag(self,tag):
1356
+ if tag in ["th", "td"]:
1357
+ stripped_content = self.last_content.strip()
1358
+ self.last_row.append(stripped_content)
1359
+ if tag == "tr":
1360
+ self.rows.append(
1361
+ (self.last_row, self.is_last_row_header))
1362
+ self.max_row_width = max(self.max_row_width, len(self.last_row))
1363
+ self.last_row = []
1364
+ self.is_last_row_header = False
1365
+ if tag == "table":
1366
+ table = self.generate_table(self.rows)
1367
+ self.tables.append(table)
1368
+ self.rows = []
1369
+ self.last_content = " "
1370
+ self.active = None
1371
+
1372
+
1373
+ def handle_data(self, data):
1374
+ self.last_content += data
1375
+
1376
+ def generate_table(self, rows):
1377
+ """
1378
+ Generates from a list of rows a PrettyTable object.
1379
+ """
1380
+ table = PrettyTable(**self.kwargs)
1381
+ for row in self.rows:
1382
+ if len(row[0]) < self.max_row_width:
1383
+ appends = self.max_row_width - len(row[0])
1384
+ for i in range(1,appends):
1385
+ row[0].append("-")
1386
+
1387
+ if row[1] == True:
1388
+ self.make_fields_unique(row[0])
1389
+ table.field_names = row[0]
1390
+ else:
1391
+ table.add_row(row[0])
1392
+ return table
1393
+
1394
+ def make_fields_unique(self, fields):
1395
+ """
1396
+ iterates over the row and make each field unique
1397
+ """
1398
+ for i in range(0, len(fields)):
1399
+ for j in range(i+1, len(fields)):
1400
+ if fields[i] == fields[j]:
1401
+ fields[j] += "'"
1402
+
1403
+ def from_html(html_code, **kwargs):
1404
+ """
1405
+ Generates a list of PrettyTables from a string of HTML code. Each <table> in
1406
+ the HTML becomes one PrettyTable object.
1407
+ """
1408
+
1409
+ parser = TableHandler(**kwargs)
1410
+ parser.feed(html_code)
1411
+ return parser.tables
1412
+
1413
+ def from_html_one(html_code, **kwargs):
1414
+ """
1415
+ Generates a PrettyTables from a string of HTML code which contains only a
1416
+ single <table>
1417
+ """
1418
+
1419
+ tables = from_html(html_code, **kwargs)
1420
+ try:
1421
+ assert len(tables) == 1
1422
+ except AssertionError:
1423
+ raise Exception("More than one <table> in provided HTML code! Use from_html instead.")
1424
+ return tables[0]
1425
+
1426
+ ##############################
1427
+ # MAIN (TEST FUNCTION) #
1428
+ ##############################
1053
1429
 
1054
1430
  def main():
1055
1431
 
1056
1432
  x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
1057
1433
  x.sortby = "Population"
1058
1434
  x.reversesort = True
1059
- x.int_format["Area"] = "04"
1060
- x.float_format = "6.1"
1435
+ x.int_format["Area"] = "04d"
1436
+ x.float_format = "6.1f"
1061
1437
  x.align["City name"] = "l" # Left align city names
1062
1438
  x.add_row(["Adelaide", 1295, 1158259, 600.5])
1063
1439
  x.add_row(["Brisbane", 5905, 1857594, 1146.4])