tony-landis (owner)

Revisions

gist: 32423 Download_button fork
public
Description:
Convert CSV string to fixed width text table
Public Clone URL: git://gist.github.com/32423.git
Embed All Files: show embed
CsvToArray.py #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""
Convert CSV string to fixed width text table. Supports multi-line rows, column width limits, and creates a header row automatically
@author Tony Landis
@link http://www.tonylandis.com
@license GPL
"""
 
from math import ceil
 
class CsvToTxt():
rows=[]; cs=[]; rs=[]; keys=[];
mH = 3; mW = 20
pcen = "+"; prow = "-"; pcol = "|"; pcolm = ":"
nline = False
 
def __init__(self, data):
x = 0
for row in data.split("\n")[:]:
self.rs.append(x)
self.rs[x]=1
cols = row.split(",")
self.rows.append(cols)
if(x==0):
self.keys = cols
for index in range(len(cols)):
self.cs.append(index);
for index, item in enumerate(cols): self.setMax(x, index, item)
x += 1;
 
def setMax(self, x, y, data):
h = 1
w = len(data)
if w > self.mW:
h = ceil(w % self.mH); w = self.mW
if self.cs[y] < w: self.cs[y] = w
if self.rs[x] < h: self.rs[x] = h
 
def printLine(self,nl=True):
if self.nline: return self.nline
else: self.nline = self.pcen
for len in self.cs[:]:
self.nline += self.prow.rjust(len, self.prow) + self.prow + self.prow + self.pcen;
return self.nline;
 
def printRow(self, rowKey):
string = ''
line=0
while line < self.rs[rowKey]:
start = self.mW * (line)
if line>0:
pcol = self.pcolm
end = self.mW+start
else:
pcol = self.pcol
end = self.mW
string = pcol
for index, item in enumerate(self.rows[rowKey]):
string += " "
string += item[start:end].ljust(self.cs[index], ' ')
string += " " + pcol
print string
line += 1
return string
 
def render(self):
for i in range(len(self.rows)):
if i == 0: print self.printLine()
self.printRow(i)
if i == 0: print self.printLine()
print self.printLine()
 
if __name__ == "__main__":
string = ''
i=0
while i < 100:
i += 1
string += "\nPython,CSV,=> Text\n100,200,300\nJack and Jill went down the hill,and ? came tumbling,after?\nHello,World,null"
f = CsvToTxt("col1,col2,col3" + string)
f.render()