| 1 |
from __future__ import absolute_import, division, print_function |
| 2 |
|
| 3 |
import re |
| 4 |
import sys |
| 5 |
from itertools import islice, chain, cycle, product,\ |
| 6 |
permutations, combinations, takewhile, dropwhile, \ |
| 7 |
starmap, groupby, tee |
| 8 |
import operator |
| 9 |
from collections import Counter, namedtuple, OrderedDict |
| 10 |
from itertools import compress, combinations_with_replacement |
| 11 |
from petl.compat import imap, izip, izip_longest, ifilter, ifilterfalse, \ |
| 12 |
reduce, next, string_types, text_type, PY3 |
| 13 |
|
| 14 |
|
| 15 |
from petl.errors import FieldSelectionError |
| 16 |
from petl.comparison import comparable_itemgetter |
| 17 |
|
| 18 |
|
| 19 |
class IterContainer(object): |
| 20 |
|
| 21 |
def __contains__(self, item): |
| 22 |
for o in self: |
| 23 |
if o == item: |
| 24 |
return True |
| 25 |
return False |
| 26 |
|
| 27 |
def __len__(self): |
| 28 |
return sum(1 for _ in self) |
| 29 |
|
| 30 |
def __getitem__(self, item): |
| 31 |
if isinstance(item, int): |
| 32 |
try: |
| 33 |
return next(islice(self, item, item+1)) |
| 34 |
except StopIteration: |
| 35 |
raise IndexError('index out of range') |
| 36 |
elif isinstance(item, slice): |
| 37 |
return islice(self, item.start, item.stop, item.step) |
| 38 |
|
| 39 |
def __iter__(self): |
| 40 |
raise NotImplementedError |
| 41 |
|
| 42 |
def index(self, item): |
| 43 |
for i, o in enumerate(self): |
| 44 |
if o == item: |
| 45 |
return i |
| 46 |
raise ValueError('%s is not in container' % item) |
| 47 |
|
| 48 |
def min(self, **kwargs): |
| 49 |
return min(self, **kwargs) |
| 50 |
|
| 51 |
def max(self, **kwargs): |
| 52 |
return max(self, **kwargs) |
| 53 |
|
| 54 |
def len(self): |
| 55 |
return len(self) |
| 56 |
|
| 57 |
def set(self): |
| 58 |
return set(self) |
| 59 |
|
| 60 |
def frozenset(self): |
| 61 |
return frozenset(self) |
| 62 |
|
| 63 |
def list(self): |
| 64 |
# avoid iterating twice |
| 65 |
return list(iter(self)) |
| 66 |
|
| 67 |
def tuple(self): |
| 68 |
# avoid iterating twice |
| 69 |
return tuple(iter(self)) |
| 70 |
|
| 71 |
def dict(self, **kwargs): |
| 72 |
return dict(self, **kwargs) |
| 73 |
|
| 74 |
def enumerate(self, start=0): |
| 75 |
return enumerate(self, start) |
| 76 |
|
| 77 |
def filter(self, function): |
| 78 |
return filter(function, self) |
| 79 |
|
| 80 |
def map(self, function): |
| 81 |
return map(function, self) |
| 82 |
|
| 83 |
def reduce(self, function, **kwargs): |
| 84 |
return reduce(function, self, **kwargs) |
| 85 |
|
| 86 |
def sum(self, *args, **kwargs): |
| 87 |
return sum(self, *args, **kwargs) |
| 88 |
|
| 89 |
def all(self): |
| 90 |
return all(self) |
| 91 |
|
| 92 |
def any(self): |
| 93 |
return any(self) |
| 94 |
|
| 95 |
def apply(self, function): |
| 96 |
for item in self: |
| 97 |
function(item) |
| 98 |
|
| 99 |
def counter(self): |
| 100 |
return Counter(self) |
| 101 |
|
| 102 |
def ordereddict(self): |
| 103 |
return OrderedDict(self) |
| 104 |
|
| 105 |
def cycle(self): |
| 106 |
return cycle(self) |
| 107 |
|
| 108 |
def chain(self, *others): |
| 109 |
return chain(self, *others) |
| 110 |
|
| 111 |
def dropwhile(self, predicate): |
| 112 |
return dropwhile(predicate, self) |
| 113 |
|
| 114 |
def takewhile(self, predicate): |
| 115 |
return takewhile(predicate, self) |
| 116 |
|
| 117 |
def ifilter(self, predicate): |
| 118 |
return ifilter(predicate, self) |
| 119 |
|
| 120 |
def ifilterfalse(self, predicate): |
| 121 |
return ifilterfalse(predicate, self) |
| 122 |
|
| 123 |
def imap(self, function): |
| 124 |
return imap(function, self) |
| 125 |
|
| 126 |
def starmap(self, function): |
| 127 |
return starmap(function, self) |
| 128 |
|
| 129 |
def islice(self, *args): |
| 130 |
return islice(self, *args) |
| 131 |
|
| 132 |
def compress(self, selectors): |
| 133 |
return compress(self, selectors) |
| 134 |
|
| 135 |
def groupby(self, *args, **kwargs): |
| 136 |
return groupby(self, *args, **kwargs) |
| 137 |
|
| 138 |
def tee(self, *args, **kwargs): |
| 139 |
return tee(self, *args, **kwargs) |
| 140 |
|
| 141 |
def permutations(self, *args, **kwargs): |
| 142 |
return permutations(self, *args, **kwargs) |
| 143 |
|
| 144 |
def combinations(self, *args, **kwargs): |
| 145 |
return combinations(self, *args, **kwargs) |
| 146 |
|
| 147 |
def combinations_with_replacement(self, *args, **kwargs): |
| 148 |
return combinations_with_replacement(self, *args, **kwargs) |
| 149 |
|
| 150 |
def izip(self, *args, **kwargs): |
| 151 |
return izip(self, *args, **kwargs) |
| 152 |
|
| 153 |
def izip_longest(self, *args, **kwargs): |
| 154 |
return izip_longest(self, *args, **kwargs) |
| 155 |
|
| 156 |
def product(self, *args, **kwargs): |
| 157 |
return product(self, *args, **kwargs) |
| 158 |
|
| 159 |
def __add__(self, other): |
| 160 |
return chain(self, other) |
| 161 |
|
| 162 |
def __iadd__(self, other): |
| 163 |
return chain(self, other) |
| 164 |
|
| 165 |
|
| 166 |
class Table(IterContainer): |
| 167 |
|
| 168 |
def __getitem__(self, item): |
| 169 |
if isinstance(item, string_types): |
| 170 |
return ValuesView(self, item) |
| 171 |
else: |
| 172 |
return super(Table, self).__getitem__(item) |
| 173 |
|
| 174 |
|
| 175 |
def values(table, *field, **kwargs): |
| 176 |
""" |
| 177 |
Return a container supporting iteration over values in a given field or |
| 178 |
fields. E.g.:: |
| 179 |
|
| 180 |
>>> import petl as etl |
| 181 |
>>> table1 = [['foo', 'bar'], |
| 182 |
... ['a', True], |
| 183 |
... ['b'], |
| 184 |
... ['b', True], |
| 185 |
... ['c', False]] |
| 186 |
>>> foo = etl.values(table1, 'foo') |
| 187 |
>>> foo |
| 188 |
foo: 'a', 'b', 'b', 'c' |
| 189 |
>>> list(foo) |
| 190 |
['a', 'b', 'b', 'c'] |
| 191 |
>>> bar = etl.values(table1, 'bar') |
| 192 |
>>> bar |
| 193 |
bar: True, None, True, False |
| 194 |
>>> list(bar) |
| 195 |
[True, None, True, False] |
| 196 |
>>> # values from multiple fields |
| 197 |
... table2 = [['foo', 'bar', 'baz'], |
| 198 |
... [1, 'a', True], |
| 199 |
... [2, 'bb', True], |
| 200 |
... [3, 'd', False]] |
| 201 |
>>> foobaz = etl.values(table2, 'foo', 'baz') |
| 202 |
>>> foobaz |
| 203 |
('foo', 'baz'): (1, True), (2, True), (3, False) |
| 204 |
>>> list(foobaz) |
| 205 |
[(1, True), (2, True), (3, False)] |
| 206 |
|
| 207 |
The field argument can be a single field name or index (starting from |
| 208 |
zero) or a tuple of field names and/or indexes. Multiple fields can also be |
| 209 |
provided as positional arguments. |
| 210 |
|
| 211 |
If rows are uneven, the value of the keyword argument `missing` is returned. |
| 212 |
|
| 213 |
""" |
| 214 |
|
| 215 |
return ValuesView(table, *field, **kwargs) |
| 216 |
|
| 217 |
|
| 218 |
Table.values = values |
| 219 |
|
| 220 |
|
| 221 |
class ValuesView(IterContainer): |
| 222 |
|
| 223 |
def __init__(self, table, *field, **kwargs): |
| 224 |
self.table = table |
| 225 |
# deal with field arg in a backwards-compatible way |
| 226 |
if len(field) == 1: |
| 227 |
field = field[0] |
| 228 |
self.field = field |
| 229 |
self.kwargs = kwargs |
| 230 |
|
| 231 |
def __iter__(self): |
| 232 |
return itervalues(self.table, self.field, **self.kwargs) |
| 233 |
|
| 234 |
def __repr__(self): |
| 235 |
vreprs = list(map(repr, islice(self, 6))) |
| 236 |
r = text_type(self.field) + ': ' |
| 237 |
r += ', '.join(vreprs[:5]) |
| 238 |
if len(vreprs) > 5: |
| 239 |
r += ', ...' |
| 240 |
return r |
| 241 |
|
| 242 |
|
| 243 |
def itervalues(table, field, **kwargs): |
| 244 |
|
| 245 |
missing = kwargs.get('missing', None) |
| 246 |
it = iter(table) |
| 247 |
try: |
| 248 |
hdr = next(it) |
| 249 |
except StopIteration: |
| 250 |
hdr = [] |
| 251 |
|
| 252 |
indices = asindices(hdr, field) |
| 253 |
assert len(indices) > 0, 'no field selected' |
| 254 |
getvalue = operator.itemgetter(*indices) |
| 255 |
for row in it: |
| 256 |
try: |
| 257 |
value = getvalue(row) |
| 258 |
yield value |
| 259 |
except IndexError: |
| 260 |
if len(indices) > 1: |
| 261 |
# try one at a time |
| 262 |
value = list() |
| 263 |
for i in indices: |
| 264 |
if i < len(row): |
| 265 |
value.append(row[i]) |
| 266 |
else: |
| 267 |
value.append(missing) |
| 268 |
yield tuple(value) |
| 269 |
else: |
| 270 |
yield missing |
| 271 |
|
| 272 |
|
| 273 |
class TableWrapper(Table): |
| 274 |
|
| 275 |
def __init__(self, inner): |
| 276 |
self.inner = inner |
| 277 |
|
| 278 |
def __iter__(self): |
| 279 |
return iter(self.inner) |
| 280 |
|
| 281 |
|
| 282 |
wrap = TableWrapper |
| 283 |
|
| 284 |
|
| 285 |
def asindices(hdr, spec): |
| 286 |
"""Convert the given field `spec` into a list of field indices.""" |
| 287 |
|
| 288 |
flds = list(map(text_type, hdr)) |
| 289 |
indices = list() |
| 290 |
if not isinstance(spec, (list, tuple)): |
| 291 |
spec = (spec,) |
| 292 |
for s in spec: |
| 293 |
# spec could be a field index (takes priority) |
| 294 |
if isinstance(s, int) and s < len(hdr): |
| 295 |
indices.append(s) # index fields from 0 |
| 296 |
# spec could be a field |
| 297 |
elif s in flds: |
| 298 |
idx = flds.index(s) |
| 299 |
indices.append(idx) |
| 300 |
flds[idx] = None # replace with None to mark as used |
| 301 |
else: |
| 302 |
raise FieldSelectionError(s) |
| 303 |
return indices |
| 304 |
|
| 305 |
|
| 306 |
def rowitemgetter(hdr, spec): |
| 307 |
indices = asindices(hdr, spec) |
| 308 |
getter = comparable_itemgetter(*indices) |
| 309 |
return getter |
| 310 |
|
| 311 |
|
| 312 |
def rowgetter(*indices): |
| 313 |
if len(indices) == 0: |
| 314 |
return lambda row: tuple() |
| 315 |
elif len(indices) == 1: |
| 316 |
# if only one index, we cannot use itemgetter, because we want a |
| 317 |
# singleton sequence to be returned, but itemgetter with a single |
| 318 |
# argument returns the value itself, so let's define a function |
| 319 |
index = indices[0] |
| 320 |
return lambda row: (row[index],) # note comma - singleton tuple |
| 321 |
# if more than one index, use itemgetter, it should be the most efficient |
| 322 |
else: |
| 323 |
return operator.itemgetter(*indices) |
| 324 |
|
| 325 |
|
| 326 |
def header(table): |
| 327 |
""" |
| 328 |
Return the header row for the given table. E.g.:: |
| 329 |
|
| 330 |
>>> import petl as etl |
| 331 |
>>> table = [['foo', 'bar'], ['a', 1], ['b', 2]] |
| 332 |
>>> etl.header(table) |
| 333 |
('foo', 'bar') |
| 334 |
|
| 335 |
Note that the header row will always be returned as a tuple, regardless |
| 336 |
of what the underlying data are. |
| 337 |
|
| 338 |
""" |
| 339 |
|
| 340 |
it = iter(table) |
| 341 |
return tuple(next(it)) |
| 342 |
|
| 343 |
|
| 344 |
Table.header = header |
| 345 |
|
| 346 |
|
| 347 |
def fieldnames(table): |
| 348 |
""" |
| 349 |
Return the string values of the header row. If the header row |
| 350 |
contains only strings, then this function is equivalent to header(), i.e.:: |
| 351 |
|
| 352 |
>>> import petl as etl |
| 353 |
>>> table = [['foo', 'bar'], ['a', 1], ['b', 2]] |
| 354 |
>>> etl.fieldnames(table) |
| 355 |
('foo', 'bar') |
| 356 |
>>> etl.header(table) |
| 357 |
('foo', 'bar') |
| 358 |
|
| 359 |
""" |
| 360 |
|
| 361 |
return tuple(text_type(f) for f in header(table)) |
| 362 |
|
| 363 |
|
| 364 |
Table.fieldnames = fieldnames |
| 365 |
|
| 366 |
|
| 367 |
def data(table, *sliceargs): |
| 368 |
""" |
| 369 |
Return a container supporting iteration over data rows in a given table |
| 370 |
(i.e., without the header). E.g.:: |
| 371 |
|
| 372 |
>>> import petl as etl |
| 373 |
>>> table = [['foo', 'bar'], ['a', 1], ['b', 2]] |
| 374 |
>>> d = etl.data(table) |
| 375 |
>>> list(d) |
| 376 |
[['a', 1], ['b', 2]] |
| 377 |
|
| 378 |
Positional arguments can be used to slice the data rows. The sliceargs |
| 379 |
are passed to :func:`itertools.islice`. |
| 380 |
|
| 381 |
""" |
| 382 |
|
| 383 |
return DataView(table, *sliceargs) |
| 384 |
|
| 385 |
|
| 386 |
Table.data = data |
| 387 |
|
| 388 |
|
| 389 |
class DataView(Table): |
| 390 |
|
| 391 |
def __init__(self, table, *sliceargs): |
| 392 |
self.table = table |
| 393 |
self.sliceargs = sliceargs |
| 394 |
|
| 395 |
def __iter__(self): |
| 396 |
return iterdata(self.table, *self.sliceargs) |
| 397 |
|
| 398 |
|
| 399 |
def iterdata(table, *sliceargs): |
| 400 |
|
| 401 |
it = islice(table, 1, None) # skip header row |
| 402 |
if sliceargs: |
| 403 |
it = islice(it, *sliceargs) |
| 404 |
return it |
| 405 |
|
| 406 |
|
| 407 |
def dicts(table, *sliceargs, **kwargs): |
| 408 |
""" |
| 409 |
Return a container supporting iteration over rows as dicts. E.g.:: |
| 410 |
|
| 411 |
>>> import petl as etl |
| 412 |
>>> table = [['foo', 'bar'], ['a', 1], ['b', 2]] |
| 413 |
>>> d = etl.dicts(table) |
| 414 |
>>> d |
| 415 |
{'foo': 'a', 'bar': 1} |
| 416 |
{'foo': 'b', 'bar': 2} |
| 417 |
>>> list(d) |
| 418 |
[{'foo': 'a', 'bar': 1}, {'foo': 'b', 'bar': 2}] |
| 419 |
|
| 420 |
Short rows are padded with the value of the `missing` keyword argument. |
| 421 |
|
| 422 |
""" |
| 423 |
|
| 424 |
return DictsView(table, *sliceargs, **kwargs) |
| 425 |
|
| 426 |
|
| 427 |
Table.dicts = dicts |
| 428 |
|
| 429 |
|
| 430 |
class DictsView(IterContainer): |
| 431 |
|
| 432 |
def __init__(self, table, *sliceargs, **kwargs): |
| 433 |
self.table = table |
| 434 |
self.sliceargs = sliceargs |
| 435 |
self.kwargs = kwargs |
| 436 |
|
| 437 |
def __iter__(self): |
| 438 |
return iterdicts(self.table, *self.sliceargs, **self.kwargs) |
| 439 |
|
| 440 |
def __repr__(self): |
| 441 |
vreprs = list(map(repr, islice(self, 6))) |
| 442 |
r = '\n'.join(vreprs[:5]) |
| 443 |
if len(vreprs) > 5: |
| 444 |
r += '\n...' |
| 445 |
return r |
| 446 |
|
| 447 |
|
| 448 |
def iterdicts(table, *sliceargs, **kwargs): |
| 449 |
missing = kwargs.get('missing', None) |
| 450 |
it = iter(table) |
| 451 |
try: |
| 452 |
hdr = next(it) |
| 453 |
except StopIteration: |
| 454 |
return |
| 455 |
if sliceargs: |
| 456 |
it = islice(it, *sliceargs) |
| 457 |
for row in it: |
| 458 |
yield asdict(hdr, row, missing) |
| 459 |
|
| 460 |
|
| 461 |
def asdict(hdr, row, missing=None): |
| 462 |
flds = [text_type(f) for f in hdr] |
| 463 |
try: |
| 464 |
# list comprehension should be faster |
| 465 |
items = [(flds[i], row[i]) for i in range(len(flds))] |
| 466 |
except IndexError: |
| 467 |
# short row, fall back to slower for loop |
| 468 |
items = list() |
| 469 |
for i, f in enumerate(flds): |
| 470 |
try: |
| 471 |
v = row[i] |
| 472 |
except IndexError: |
| 473 |
v = missing |
| 474 |
items.append((f, v)) |
| 475 |
return dict(items) |
| 476 |
|
| 477 |
|
| 478 |
def namedtuples(table, *sliceargs, **kwargs): |
| 479 |
""" |
| 480 |
View the table as a container of named tuples. E.g.:: |
| 481 |
|
| 482 |
>>> import petl as etl |
| 483 |
>>> table = [['foo', 'bar'], ['a', 1], ['b', 2]] |
| 484 |
>>> d = etl.namedtuples(table) |
| 485 |
>>> d |
| 486 |
row(foo='a', bar=1) |
| 487 |
row(foo='b', bar=2) |
| 488 |
>>> list(d) |
| 489 |
[row(foo='a', bar=1), row(foo='b', bar=2)] |
| 490 |
|
| 491 |
Short rows are padded with the value of the `missing` keyword argument. |
| 492 |
|
| 493 |
The `name` keyword argument can be given to override the name of the |
| 494 |
named tuple class (defaults to 'row'). |
| 495 |
|
| 496 |
""" |
| 497 |
|
| 498 |
return NamedTuplesView(table, *sliceargs, **kwargs) |
| 499 |
|
| 500 |
|
| 501 |
Table.namedtuples = namedtuples |
| 502 |
|
| 503 |
|
| 504 |
class NamedTuplesView(IterContainer): |
| 505 |
|
| 506 |
def __init__(self, table, *sliceargs, **kwargs): |
| 507 |
self.table = table |
| 508 |
self.sliceargs = sliceargs |
| 509 |
self.kwargs = kwargs |
| 510 |
|
| 511 |
def __iter__(self): |
| 512 |
return iternamedtuples(self.table, *self.sliceargs, **self.kwargs) |
| 513 |
|
| 514 |
def __repr__(self): |
| 515 |
vreprs = list(map(repr, islice(self, 6))) |
| 516 |
r = '\n'.join(vreprs[:5]) |
| 517 |
if len(vreprs) > 5: |
| 518 |
r += '\n...' |
| 519 |
return r |
| 520 |
|
| 521 |
|
| 522 |
def iternamedtuples(table, *sliceargs, **kwargs): |
| 523 |
missing = kwargs.get('missing', None) |
| 524 |
name = kwargs.get('name', 'row') |
| 525 |
it = iter(table) |
| 526 |
try: |
| 527 |
hdr = next(it) |
| 528 |
except StopIteration: |
| 529 |
return |
| 530 |
flds = list(map(text_type, hdr)) |
| 531 |
nt = namedtuple(name, tuple(flds)) |
| 532 |
if sliceargs: |
| 533 |
it = islice(it, *sliceargs) |
| 534 |
for row in it: |
| 535 |
yield asnamedtuple(nt, row, missing) |
| 536 |
|
| 537 |
|
| 538 |
def asnamedtuple(nt, row, missing=None): |
| 539 |
try: |
| 540 |
return nt(*row) |
| 541 |
except TypeError: |
| 542 |
# row may be long or short |
| 543 |
# expected number of fields |
| 544 |
ne = len(nt._fields) |
| 545 |
# actual number of values |
| 546 |
na = len(row) |
| 547 |
if ne > na: |
| 548 |
# pad short rows |
| 549 |
padded = tuple(row) + (missing,) * (ne-na) |
| 550 |
return nt(*padded) |
| 551 |
elif ne < na: |
| 552 |
# truncate long rows |
| 553 |
return nt(*row[:ne]) |
| 554 |
else: |
| 555 |
raise |
| 556 |
|
| 557 |
|
| 558 |
class Record(tuple): |
| 559 |
|
| 560 |
def __new__(cls, row, flds, missing=None): |
| 561 |
t = super(Record, cls).__new__(cls, row) |
| 562 |
return t |
| 563 |
|
| 564 |
def __init__(self, row, flds, missing=None): |
| 565 |
self.flds = flds |
| 566 |
self.missing = missing |
| 567 |
|
| 568 |
def __getitem__(self, f): |
| 569 |
if isinstance(f, int): |
| 570 |
idx = f |
| 571 |
elif f in self.flds: |
| 572 |
idx = self.flds.index(f) |
| 573 |
else: |
| 574 |
raise KeyError('item ' + repr(f) + |
| 575 |
' not in fields ' + repr(self.flds)) |
| 576 |
try: |
| 577 |
return super(Record, self).__getitem__(idx) |
| 578 |
except IndexError: # handle short rows |
| 579 |
return self.missing |
| 580 |
|
| 581 |
def __getattr__(self, f): |
| 582 |
if f in self.flds: |
| 583 |
try: |
| 584 |
return super(Record, self).__getitem__(self.flds.index(f)) |
| 585 |
except IndexError: # handle short rows |
| 586 |
return self.missing |
| 587 |
else: |
| 588 |
raise AttributeError('item ' + repr(f) + |
| 589 |
' not in fields ' + repr(self.flds)) |
| 590 |
|
| 591 |
def get(self, key, default=None): |
| 592 |
try: |
| 593 |
return self[key] |
| 594 |
except KeyError: |
| 595 |
return default |
| 596 |
|
| 597 |
|
| 598 |
def records(table, *sliceargs, **kwargs): |
| 599 |
""" |
| 600 |
Return a container supporting iteration over rows as records, where a |
| 601 |
record is a hybrid object supporting all possible ways of accessing values. |
| 602 |
E.g.:: |
| 603 |
|
| 604 |
|
| 605 |
>>> import petl as etl |
| 606 |
>>> table = [['foo', 'bar'], ['a', 1], ['b', 2]] |
| 607 |
>>> d = etl.records(table) |
| 608 |
>>> d |
| 609 |
('a', 1) |
| 610 |
('b', 2) |
| 611 |
>>> list(d) |
| 612 |
[('a', 1), ('b', 2)] |
| 613 |
>>> [r[0] for r in d] |
| 614 |
['a', 'b'] |
| 615 |
>>> [r['foo'] for r in d] |
| 616 |
['a', 'b'] |
| 617 |
>>> [r.foo for r in d] |
| 618 |
['a', 'b'] |
| 619 |
|
| 620 |
Short rows are padded with the value of the `missing` keyword argument. |
| 621 |
|
| 622 |
""" |
| 623 |
|
| 624 |
return RecordsView(table, *sliceargs, **kwargs) |
| 625 |
|
| 626 |
|
| 627 |
Table.records = records |
| 628 |
|
| 629 |
|
| 630 |
class RecordsView(IterContainer): |
| 631 |
|
| 632 |
def __init__(self, table, *sliceargs, **kwargs): |
| 633 |
self.table = table |
| 634 |
self.sliceargs = sliceargs |
| 635 |
self.kwargs = kwargs |
| 636 |
|
| 637 |
def __iter__(self): |
| 638 |
return iterrecords(self.table, *self.sliceargs, **self.kwargs) |
| 639 |
|
| 640 |
def __repr__(self): |
| 641 |
vreprs = list(map(repr, islice(self, 6))) |
| 642 |
r = '\n'.join(vreprs[:5]) |
| 643 |
if len(vreprs) > 5: |
| 644 |
r += '\n...' |
| 645 |
return r |
| 646 |
|
| 647 |
|
| 648 |
def iterrecords(table, *sliceargs, **kwargs): |
| 649 |
missing = kwargs.get('missing', None) |
| 650 |
it = iter(table) |
| 651 |
try: |
| 652 |
hdr = next(it) |
| 653 |
except StopIteration: |
| 654 |
return |
| 655 |
flds = list(map(text_type, hdr)) |
| 656 |
if sliceargs: |
| 657 |
it = islice(it, *sliceargs) |
| 658 |
for row in it: |
| 659 |
yield Record(row, flds, missing=missing) |
| 660 |
|
| 661 |
|
| 662 |
_RESTRICTED = None |
| 663 |
_expr_impl = None |
| 664 |
_expr_regex = None |
| 665 |
|
| 666 |
|
| 667 |
def expr(expression_text, trusted=True): |
| 668 |
""" |
| 669 |
Construct a function operating on a table record. |
| 670 |
|
| 671 |
The expression string is converted into a lambda function by prepending |
| 672 |
the string with ``'lambda rec: '``, then replacing anything enclosed in |
| 673 |
curly braces (e.g., ``"{foo}"``) with a lookup on the record (e.g., |
| 674 |
``"rec['foo']"``), then finally calling :func:`eval`. |
| 675 |
|
| 676 |
So, e.g., the expression string ``"{foo} * {bar}"`` is converted to the |
| 677 |
function ``lambda rec: rec['foo'] * rec['bar']`` |
| 678 |
|
| 679 |
The ``trusted`` keyword argument can be used to specify whether the |
| 680 |
expression is trusted and doesn't contains any type of code injection. |
| 681 |
If the expression is trusted, it will be evaluated using ``eval``, |
| 682 |
otherwise it will be evaluated using the `asteval` library if available. |
| 683 |
|
| 684 |
Note that in further versions of petl, the default value of ``trusted`` |
| 685 |
will change to ``False``. |
| 686 |
""" |
| 687 |
|
| 688 |
global _expr_impl |
| 689 |
if _expr_impl is None: |
| 690 |
_expr_impl = _unsafe_expr |
| 691 |
if trusted is not None and not trusted and PY3: |
| 692 |
try: |
| 693 |
import asteval # noqa: F401 |
| 694 |
_expr_impl = _safe_expr |
| 695 |
except ImportError: |
| 696 |
pass |
| 697 |
|
| 698 |
def _expr_repl(matchobj): |
| 699 |
return "rec['%s']" % matchobj.group(1) |
| 700 |
|
| 701 |
global _expr_regex |
| 702 |
if _expr_regex is None: |
| 703 |
_expr_regex = re.compile(r'\{([^}]+)\}') |
| 704 |
strexpr = _expr_regex.sub(_expr_repl, expression_text) |
| 705 |
|
| 706 |
return _expr_impl(strexpr) |
| 707 |
|
| 708 |
|
| 709 |
class PetlAstEval(object): |
| 710 |
def __init__(self, expression_text): |
| 711 |
from asteval import Interpreter |
| 712 |
|
| 713 |
self.aeval = Interpreter() |
| 714 |
code = "def expr(rec):\n return %s\n" % expression_text |
| 715 |
self.aeval(code) |
| 716 |
|
| 717 |
def __repr__(self): |
| 718 |
return self.aeval.expr |
| 719 |
|
| 720 |
def __call__(self, rec): |
| 721 |
self.aeval.symtable['rec'] = rec |
| 722 |
evaluated = self.aeval("expr(rec)") |
| 723 |
if len(self.aeval.error) > 0: |
| 724 |
err = [e.get_error()[-1] for e in self.aeval.error] |
| 725 |
msg = "\n".join(err) |
| 726 |
raise ValueError("Failed to evaluate expression due to: %s" % msg) |
| 727 |
return evaluated |
| 728 |
|
| 729 |
def _safe_expr(expression_text): |
| 730 |
evaluator = PetlAstEval(expression_text) |
| 731 |
return evaluator |
| 732 |
|
| 733 |
|
| 734 |
def _unsafe_expr(expression_text): |
| 735 |
|
| 736 |
global _RESTRICTED |
| 737 |
if _RESTRICTED is None: |
| 738 |
_RESTRICTED = { |
| 739 |
"__builtins__": None, |
| 740 |
"__class__": None, |
| 741 |
"__package__": None, |
| 742 |
"__loader__": None, |
| 743 |
"__spec__": None, |
| 744 |
"__file__": None, |
| 745 |
"__cached__": None, |
| 746 |
"__dict__": None, |
| 747 |
"__import__": None, |
| 748 |
"__path__": None, |
| 749 |
"__main__": None, |
| 750 |
"__name__": None, |
| 751 |
"__doc__": None |
| 752 |
} |
| 753 |
nomods = {k: None for k in sys.modules if "." not in k} |
| 754 |
_RESTRICTED.update(nomods) |
| 755 |
|
| 756 |
strexpr = "lambda rec: " + expression_text |
| 757 |
try: |
| 758 |
fun = eval(strexpr, _RESTRICTED, _RESTRICTED) |
| 759 |
return fun |
| 760 |
except ValueError as ve: |
| 761 |
raise ValueError('Invalid expression: "%s" causes error: %s' % (strexpr, ve)) |
| 762 |
|
| 763 |
|
| 764 |
def rowgroupby(table, key, value=None): |
| 765 |
"""Convenient adapter for :func:`itertools.groupby`. E.g.:: |
| 766 |
|
| 767 |
>>> import petl as etl |
| 768 |
>>> table1 = [['foo', 'bar', 'baz'], |
| 769 |
... ['a', 1, True], |
| 770 |
... ['b', 3, True], |
| 771 |
... ['b', 2]] |
| 772 |
>>> # group entire rows |
| 773 |
... for key, group in etl.rowgroupby(table1, 'foo'): |
| 774 |
... print(key, list(group)) |
| 775 |
... |
| 776 |
a [('a', 1, True)] |
| 777 |
b [('b', 3, True), ('b', 2)] |
| 778 |
>>> # group specific values |
| 779 |
... for key, group in etl.rowgroupby(table1, 'foo', 'bar'): |
| 780 |
... print(key, list(group)) |
| 781 |
... |
| 782 |
a [1] |
| 783 |
b [3, 2] |
| 784 |
|
| 785 |
N.B., assumes the input table is already sorted by the given key. |
| 786 |
|
| 787 |
""" |
| 788 |
|
| 789 |
it = iter(table) |
| 790 |
try: |
| 791 |
hdr = next(it) |
| 792 |
except StopIteration: |
| 793 |
hdr = [] |
| 794 |
flds = list(map(text_type, hdr)) |
| 795 |
# wrap rows as records |
| 796 |
it = (Record(row, flds) for row in it) |
| 797 |
|
| 798 |
# determine key function |
| 799 |
if callable(key): |
| 800 |
getkey = key |
| 801 |
native_key = True |
| 802 |
else: |
| 803 |
kindices = asindices(hdr, key) |
| 804 |
getkey = comparable_itemgetter(*kindices) |
| 805 |
native_key = False |
| 806 |
|
| 807 |
git = groupby(it, key=getkey) |
| 808 |
if value is None: |
| 809 |
if native_key: |
| 810 |
return git |
| 811 |
else: |
| 812 |
return ((k.inner, vals) for (k, vals) in git) |
| 813 |
else: |
| 814 |
if callable(value): |
| 815 |
getval = value |
| 816 |
else: |
| 817 |
vindices = asindices(hdr, value) |
| 818 |
getval = operator.itemgetter(*vindices) |
| 819 |
if native_key: |
| 820 |
return ((k, (getval(v) for v in vals)) |
| 821 |
for (k, vals) in git) |
| 822 |
else: |
| 823 |
return ((k.inner, (getval(v) for v in vals)) |
| 824 |
for (k, vals) in git) |
| 825 |
|
| 826 |
|
| 827 |
Table.rowgroupby = rowgroupby |
| 828 |
|
| 829 |
|
| 830 |
def iterpeek(it, n=1): |
| 831 |
it = iter(it) # make sure it's an iterator |
| 832 |
if n == 1: |
| 833 |
peek = next(it) |
| 834 |
return peek, chain([peek], it) |
| 835 |
else: |
| 836 |
peek = list(islice(it, n)) |
| 837 |
return peek, chain(peek, it) |
| 838 |
|
| 839 |
|
| 840 |
def empty(): |
| 841 |
""" |
| 842 |
Return an empty table. Can be useful when building up a table from a set |
| 843 |
of columns, e.g.:: |
| 844 |
|
| 845 |
>>> import petl as etl |
| 846 |
>>> table = ( |
| 847 |
... etl |
| 848 |
... .empty() |
| 849 |
... .addcolumn('foo', ['A', 'B']) |
| 850 |
... .addcolumn('bar', [1, 2]) |
| 851 |
... ) |
| 852 |
>>> table |
| 853 |
+-----+-----+ |
| 854 |
| foo | bar | |
| 855 |
+=====+=====+ |
| 856 |
| 'A' | 1 | |
| 857 |
+-----+-----+ |
| 858 |
| 'B' | 2 | |
| 859 |
+-----+-----+ |
| 860 |
|
| 861 |
""" |
| 862 |
|
| 863 |
return EmptyTable() |
| 864 |
|
| 865 |
|
| 866 |
class EmptyTable(Table): |
| 867 |
|
| 868 |
def __iter__(self): |
| 869 |
# empty header row |
| 870 |
yield tuple() |