forked from wireservice/csvkit
/
table.py
273 lines (213 loc) · 8.15 KB
/
table.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
#!/usr/bin/env python
import datetime
from cStringIO import StringIO
import itertools
from csvkit import CSVKitReader, CSVKitWriter
from csvkit import sniffer
from csvkit import typeinference
from csvkit.cli import parse_column_identifiers
from csvkit.headers import make_default_headers
class InvalidType(object):
"""
Dummy object type for Column initialization, since None is being used as a valid value.
"""
pass
class Column(list):
"""
A normalized data column and inferred annotations (nullable, etc.).
"""
def __init__(self, order, name, l, normal_type=InvalidType, blanks_as_nulls=True, infer_types=True):
"""
Construct a column from a sequence of values.
If normal_type is not InvalidType, inference will be skipped and values assumed to have already been normalized.
If infer_types is False, type inference will be skipped and the type assumed to be unicode.
"""
if normal_type != InvalidType:
t = normal_type
data = l
elif not infer_types:
t = unicode
data = l
else:
t, data = typeinference.normalize_column_type(l, blanks_as_nulls=blanks_as_nulls)
list.__init__(self, data)
self.order = order
self.name = name or '_unnamed' # empty column names don't make sense
self.type = t
def __str__(self):
return str(self.__unicode__())
def __unicode__(self):
"""
Stringify a description of this column.
"""
return u'%3i: %s (%s)' % (self.order, self.name, self.type)
def __getitem__(self, key):
"""
Return null for keys beyond the range of the column. This allows for columns to be of uneven length and still be merged into rows cleanly.
"""
if key >= len(self):
return None
return list.__getitem__(self, key)
def has_nulls(self):
"""
Check if this column contains nulls.
"""
return True if None in self else False
def max_length(self):
"""
Compute maximum length of data in this column.
Returns 0 if the column does not of type ``unicode``.
"""
l = 0
if self.type == unicode:
l = max([len(d) if d else 0 for d in self])
if self.has_nulls():
l = max(l, 4) # "None"
return l
class Table(list):
"""
A normalized data table and inferred annotations (nullable, etc.).
"""
def __init__(self, columns=[], name='new_table'):
"""
Generic constructor. You should normally use a from_* method to create a Table.
"""
list.__init__(self, columns)
self.name = name
def __str__(self):
return str(self.__unicode__())
def __unicode__(self):
"""
Stringify a description of all columns in this table.
"""
return u'\n'.join([unicode(c) for c in self])
def _reindex_columns(self):
"""
Update order properties of all columns in table.
"""
for i, c in enumerate(self):
c.order = i
def _deduplicate_column_name(self, column):
while column.name in self.headers():
try:
i = column.name.rindex('_')
counter = int(column.name[i + 1:])
column.name = '%s_%i' % (column.name[:i], counter + 1)
except:
column.name += '_2'
return column.name
def append(self, column):
"""Implements list append."""
self._deduplicate_column_name(column)
list.append(self, column)
column.index = len(self) - 1
def insert(self, i, column):
"""Implements list insert."""
self._deduplicate_column_name(column)
list.insert(self, i, column)
self._reindex_columns()
def extend(self, columns):
"""Implements list extend."""
for c in columns:
self._deduplicate_column_name(c)
list.extend(self, columns)
self._reindex_columns()
def remove(self, column):
"""Implements list remove."""
list.remove(self, column)
self._reindex_columns()
def sort(self):
"""Forbids list sort."""
raise NotImplementedError()
def reverse(self):
"""Forbids list reverse."""
raise NotImplementedError()
def headers(self):
return [c.name for c in self]
def count_rows(self):
lengths = [len(c) for c in self]
if lengths:
return max(lengths)
return 0
def row(self, i):
"""
Fetch a row of data from this table.
"""
if i < 0:
raise IndexError('Negative row numbers are not valid.')
if i >= self.count_rows():
raise IndexError('Row number exceeds the number of rows in the table.')
row_data = [c[i] for c in self]
return row_data
@classmethod
def from_csv(cls, f, name='from_csv_table', snifflimit=None, column_ids=None, blanks_as_nulls=True, zero_based=False, infer_types=True, no_header_row=False, **kwargs):
"""
Creates a new Table from a file-like object containing CSV data.
Note: the column_ids argument will cause only those columns with a matching identifier
to be parsed, type inferred, etc. However, their order/index property will reflect the
original data (e.g. column 8 will still be "order" 7, even if it's the third column
in the resulting Table.
"""
# This bit of nonsense is to deal with "files" from stdin,
# which are not seekable and thus must be buffered
contents = f.read()
# snifflimit == 0 means do not sniff
if snifflimit is None:
kwargs['dialect'] = sniffer.sniff_dialect(contents)
elif snifflimit > 0:
kwargs['dialect'] = sniffer.sniff_dialect(contents[:snifflimit])
f = StringIO(contents)
rows = CSVKitReader(f, **kwargs)
if no_header_row:
# Peek at a row to infer column names from
row = next(rows)
headers = make_default_headers(len(row))
column_ids = range(len(row))
data_columns = [[] for c in headers]
# Put row back on top
rows = itertools.chain([row], rows)
else:
headers = rows.next()
if column_ids:
column_ids = parse_column_identifiers(column_ids, headers, zero_based)
headers = [headers[c] for c in column_ids]
else:
column_ids = range(len(headers))
data_columns = [[] for c in headers]
for i, row in enumerate(rows):
for j, d in enumerate(row):
try:
data_columns[j].append(row[column_ids[j]].strip())
except IndexError:
# Non-rectangular data is truncated
break
columns = []
for i, c in enumerate(data_columns):
columns.append(Column(column_ids[i], headers[i], c, blanks_as_nulls=blanks_as_nulls, infer_types=infer_types))
return Table(columns, name=name)
def to_rows(self, serialize_dates=False):
"""
Generates rows from columns and performs.
Optionally serialize date objects to isoformat strings.
"""
if serialize_dates:
out_columns = []
for c in self:
# Stringify datetimes, dates, and times
if c.type in [datetime.datetime, datetime.date, datetime.time]:
out_columns.append([unicode(v.isoformat()) if v != None else None for v in c])
else:
out_columns.append(c)
# Convert columns to rows
return zip(*out_columns)
else:
return zip(*self)
def to_csv(self, output, **kwargs):
"""
Serializes the table to CSV and writes it to any file-like object.
"""
rows = self.to_rows(serialize_dates=True)
# Insert header row
rows.insert(0, self.headers())
writer = CSVKitWriter(output, **kwargs)
writer.writerows(rows)