Debian Codegraph @

petl/transform/regex.py

raw
1 from __future__ import absolute_import, print_function, division
2
3
4 import re
5 import operator
6 from petl.compat import next, text_type
7
8
9 from petl.errors import ArgumentError
10 from petl.util.base import Table, asindices
11 from petl.transform.basics import TransformError
12 from petl.transform.conversions import convert
13
14
15 def capture(table, field, pattern, newfields=None, include_original=False,
16 flags=0, fill=None):
17 """
18 Add one or more new fields with values captured from an existing field
19 searched via a regular expression. E.g.::
20
21 >>> import petl as etl
22 >>> table1 = [['id', 'variable', 'value'],
23 ... ['1', 'A1', '12'],
24 ... ['2', 'A2', '15'],
25 ... ['3', 'B1', '18'],
26 ... ['4', 'C12', '19']]
27 >>> table2 = etl.capture(table1, 'variable', '([A-Z,a-z]+)([0-9]+)',
28 ... ['treat', 'time'])
29 >>> table2
30 +-----+-------+-------+------+
31 | id | value | treat | time |
32 +=====+=======+=======+======+
33 | '1' | '12' | 'A' | '1' |
34 +-----+-------+-------+------+
35 | '2' | '15' | 'A' | '2' |
36 +-----+-------+-------+------+
37 | '3' | '18' | 'B' | '1' |
38 +-----+-------+-------+------+
39 | '4' | '19' | 'C' | '12' |
40 +-----+-------+-------+------+
41
42 >>> # using the include_original argument
43 ... table3 = etl.capture(table1, 'variable', '([A-Z,a-z]+)([0-9]+)',
44 ... ['treat', 'time'],
45 ... include_original=True)
46 >>> table3
47 +-----+----------+-------+-------+------+
48 | id | variable | value | treat | time |
49 +=====+==========+=======+=======+======+
50 | '1' | 'A1' | '12' | 'A' | '1' |
51 +-----+----------+-------+-------+------+
52 | '2' | 'A2' | '15' | 'A' | '2' |
53 +-----+----------+-------+-------+------+
54 | '3' | 'B1' | '18' | 'B' | '1' |
55 +-----+----------+-------+-------+------+
56 | '4' | 'C12' | '19' | 'C' | '12' |
57 +-----+----------+-------+-------+------+
58
59 By default the field on which the capture is performed is omitted. It can
60 be included using the `include_original` argument.
61
62 The ``fill`` parameter can be used to provide a list or tuple of values to
63 use if the regular expression does not match. The ``fill`` parameter
64 should contain as many values as there are capturing groups in the regular
65 expression. If ``fill`` is ``None`` (default) then a
66 ``petl.transform.TransformError`` will be raised on the first non-matching
67 value.
68 """
69
70 return CaptureView(table, field, pattern,
71 newfields=newfields,
72 include_original=include_original,
73 flags=flags,
74 fill=fill)
75
76
77 Table.capture = capture
78
79
80 class CaptureView(Table):
81
82 def __init__(self, source, field, pattern, newfields=None,
83 include_original=False, flags=0, fill=None):
84 self.source = source
85 self.field = field
86 self.pattern = pattern
87 self.newfields = newfields
88 self.include_original = include_original
89 self.flags = flags
90 self.fill = fill
91
92 def __iter__(self):
93 return itercapture(self.source, self.field, self.pattern,
94 self.newfields, self.include_original, self.flags,
95 self.fill)
96
97
98 def itercapture(source, field, pattern, newfields, include_original, flags,
99 fill):
100 it = iter(source)
101 prog = re.compile(pattern, flags)
102
103 try:
104 hdr = next(it)
105 except StopIteration:
106 hdr = []
107 flds = list(map(text_type, hdr))
108 if isinstance(field, int) and field < len(hdr):
109 field_index = field
110 elif field in flds:
111 field_index = flds.index(field)
112 else:
113 raise ArgumentError('field invalid: must be either field name or index')
114
115 # determine output fields
116 outhdr = list(flds)
117 if not include_original:
118 outhdr.remove(field)
119 if newfields:
120 outhdr.extend(newfields)
121 yield tuple(outhdr)
122
123 # construct the output data
124 for row in it:
125 value = row[field_index]
126 if include_original:
127 out_row = list(row)
128 else:
129 out_row = [v for i, v in enumerate(row) if i != field_index]
130 # None is a missing cell; treat as non-matching like an empty miss.
131 match = None if value is None else prog.search(value)
132 if match is None:
133 if fill is not None:
134 out_row.extend(fill)
135 else:
136 raise TransformError('value %r did not match pattern %r'
137 % (value, pattern))
138 else:
139 out_row.extend(match.groups())
140 yield tuple(out_row)
141
142
143 def split(table, field, pattern, newfields=None, include_original=False,
144 maxsplit=0, flags=0):
145 """
146 Add one or more new fields with values generated by splitting an
147 existing value around occurrences of a regular expression. E.g.::
148
149 >>> import petl as etl
150 >>> table1 = [['id', 'variable', 'value'],
151 ... ['1', 'parad1', '12'],
152 ... ['2', 'parad2', '15'],
153 ... ['3', 'tempd1', '18'],
154 ... ['4', 'tempd2', '19']]
155 >>> table2 = etl.split(table1, 'variable', 'd', ['variable', 'day'])
156 >>> table2
157 +-----+-------+----------+-----+
158 | id | value | variable | day |
159 +=====+=======+==========+=====+
160 | '1' | '12' | 'para' | '1' |
161 +-----+-------+----------+-----+
162 | '2' | '15' | 'para' | '2' |
163 +-----+-------+----------+-----+
164 | '3' | '18' | 'temp' | '1' |
165 +-----+-------+----------+-----+
166 | '4' | '19' | 'temp' | '2' |
167 +-----+-------+----------+-----+
168
169 By default the field on which the split is performed is omitted. It can
170 be included using the `include_original` argument.
171
172 """
173
174 return SplitView(table, field, pattern, newfields, include_original,
175 maxsplit, flags)
176
177
178 Table.split = split
179
180
181 class SplitView(Table):
182
183 def __init__(self, source, field, pattern, newfields=None,
184 include_original=False, maxsplit=0, flags=0):
185 self.source = source
186 self.field = field
187 self.pattern = pattern
188 self.newfields = newfields
189 self.include_original = include_original
190 self.maxsplit = maxsplit
191 self.flags = flags
192
193 def __iter__(self):
194 return itersplit(self.source, self.field, self.pattern, self.newfields,
195 self.include_original, self.maxsplit, self.flags)
196
197
198 def itersplit(source, field, pattern, newfields, include_original, maxsplit,
199 flags):
200
201 it = iter(source)
202 prog = re.compile(pattern, flags)
203
204 try:
205 hdr = next(it)
206 except StopIteration:
207 hdr = []
208 flds = list(map(text_type, hdr))
209 if isinstance(field, int) and field < len(hdr):
210 field_index = field
211 field = hdr[field_index]
212 elif field in flds:
213 field_index = flds.index(field)
214 else:
215 raise ArgumentError('field invalid: must be either field name or index')
216
217 # determine output fields
218 outhdr = list(flds)
219 if not include_original:
220 outhdr.remove(field)
221 if newfields:
222 outhdr.extend(newfields)
223 yield tuple(outhdr)
224
225 # construct the output data
226 for row in it:
227 value = row[field_index]
228 if include_original:
229 out_row = list(row)
230 else:
231 out_row = [v for i, v in enumerate(row) if i != field_index]
232 out_row.extend(prog.split(value, maxsplit))
233 yield tuple(out_row)
234
235
236 def sub(table, field, pattern, repl, count=0, flags=0):
237 """
238 Convenience function to convert values under the given field using a
239 regular expression substitution. See also :func:`re.sub`.
240
241 """
242
243 prog = re.compile(pattern, flags)
244 conv = lambda v: prog.sub(repl, v, count=count)
245 return convert(table, field, conv)
246
247
248 Table.sub = sub
249
250
251 def search(table, *args, **kwargs):
252 """
253 Perform a regular expression search, returning rows that match a given
254 pattern, either anywhere in the row or within a specific field. E.g.::
255
256 >>> import petl as etl
257 >>> table1 = [['foo', 'bar', 'baz'],
258 ... ['orange', 12, 'oranges are nice fruit'],
259 ... ['mango', 42, 'I like them'],
260 ... ['banana', 74, 'lovely too'],
261 ... ['cucumber', 41, 'better than mango']]
262 >>> # search any field
263 ... table2 = etl.search(table1, '.g.')
264 >>> table2
265 +------------+-----+--------------------------+
266 | foo | bar | baz |
267 +============+=====+==========================+
268 | 'orange' | 12 | 'oranges are nice fruit' |
269 +------------+-----+--------------------------+
270 | 'mango' | 42 | 'I like them' |
271 +------------+-----+--------------------------+
272 | 'cucumber' | 41 | 'better than mango' |
273 +------------+-----+--------------------------+
274
275 >>> # search a specific field
276 ... table3 = etl.search(table1, 'foo', '.g.')
277 >>> table3
278 +----------+-----+--------------------------+
279 | foo | bar | baz |
280 +==========+=====+==========================+
281 | 'orange' | 12 | 'oranges are nice fruit' |
282 +----------+-----+--------------------------+
283 | 'mango' | 42 | 'I like them' |
284 +----------+-----+--------------------------+
285
286 The complement can be found via
287 :func:`petl.transform.regex.searchcomplement`.
288
289 """
290
291 if len(args) == 1:
292 field = None
293 pattern = args[0]
294 elif len(args) == 2:
295 field = args[0]
296 pattern = args[1]
297 else:
298 raise ArgumentError('expected 1 or 2 positional arguments')
299 return SearchView(table, pattern, field=field, **kwargs)
300
301
302 Table.search = search
303
304
305 class SearchView(Table):
306
307 def __init__(self, table, pattern, field=None, flags=0, complement=False):
308 self.table = table
309 self.pattern = pattern
310 self.field = field
311 self.flags = flags
312 self.complement = complement
313
314 def __iter__(self):
315 return itersearch(self.table, self.pattern, self.field, self.flags,
316 self.complement)
317
318
319 def itersearch(table, pattern, field, flags, complement):
320 prog = re.compile(pattern, flags)
321 it = iter(table)
322 try:
323 hdr = next(it)
324 except StopIteration:
325 return
326 flds = list(map(text_type, hdr))
327 yield tuple(hdr)
328
329 if field is None:
330 # search whole row
331 test = lambda r: any(prog.search(text_type(v)) for v in r)
332 else:
333 indices = asindices(hdr, field)
334 if len(indices) == 1:
335 index = indices[0]
336 test = lambda r: prog.search(text_type(r[index]))
337 else:
338 getvals = operator.itemgetter(*indices)
339 test = lambda r: any(prog.search(text_type(v)) for v in getvals(r))
340 # complement==False, return rows that match
341 if not complement:
342 for row in it:
343 if test(row):
344 yield tuple(row)
345 # complement==True, return rows that do not match
346 else:
347 for row in it:
348 if not test(row):
349 yield tuple(row)
350
351
352 def searchcomplement(table, *args, **kwargs):
353 """
354 Perform a regular expression search, returning rows that **do not**
355 match a given pattern, either anywhere in the row or within a specific
356 field. E.g.::
357
358 >>> import petl as etl
359 >>> table1 = [['foo', 'bar', 'baz'],
360 ... ['orange', 12, 'oranges are nice fruit'],
361 ... ['mango', 42, 'I like them'],
362 ... ['banana', 74, 'lovely too'],
363 ... ['cucumber', 41, 'better than mango']]
364 >>> # search any field
365 ... table2 = etl.searchcomplement(table1, '.g.')
366 >>> table2
367 +----------+-----+--------------+
368 | foo | bar | baz |
369 +==========+=====+==============+
370 | 'banana' | 74 | 'lovely too' |
371 +----------+-----+--------------+
372
373 >>> # search a specific field
374 ... table3 = etl.searchcomplement(table1, 'foo', '.g.')
375 >>> table3
376 +------------+-----+---------------------+
377 | foo | bar | baz |
378 +============+=====+=====================+
379 | 'banana' | 74 | 'lovely too' |
380 +------------+-----+---------------------+
381 | 'cucumber' | 41 | 'better than mango' |
382 +------------+-----+---------------------+
383
384 This returns the complement of :func:`petl.transform.regex.search`.
385
386 """
387
388 return search(table, *args, complement=True, **kwargs)
389
390
391 Table.searchcomplement = searchcomplement
392
393
394 def splitdown(table, field, pattern, maxsplit=0, flags=0):
395 """
396 Split a field into multiple rows using a regular expression. E.g.:
397
398 >>> import petl as etl
399 >>> table1 = [['name', 'roles'],
400 ... ['Jane Doe', 'president,engineer,tailor,lawyer'],
401 ... ['John Doe', 'rocket scientist,optometrist,chef,knight,sailor']]
402 >>> table2 = etl.splitdown(table1, 'roles', ',')
403 >>> table2.lookall()
404 +------------+--------------------+
405 | name | roles |
406 +============+====================+
407 | 'Jane Doe' | 'president' |
408 +------------+--------------------+
409 | 'Jane Doe' | 'engineer' |
410 +------------+--------------------+
411 | 'Jane Doe' | 'tailor' |
412 +------------+--------------------+
413 | 'Jane Doe' | 'lawyer' |
414 +------------+--------------------+
415 | 'John Doe' | 'rocket scientist' |
416 +------------+--------------------+
417 | 'John Doe' | 'optometrist' |
418 +------------+--------------------+
419 | 'John Doe' | 'chef' |
420 +------------+--------------------+
421 | 'John Doe' | 'knight' |
422 +------------+--------------------+
423 | 'John Doe' | 'sailor' |
424 +------------+--------------------+
425
426 """
427
428 return SplitDownView(table, field, pattern, maxsplit, flags)
429
430
431 Table.splitdown = splitdown
432
433
434 class SplitDownView(Table):
435
436 def __init__(self, table, field, pattern, maxsplit=0, flags=0):
437 self.table = table
438 self.field = field
439 self.pattern = pattern
440 self.maxsplit = maxsplit
441 self.flags = flags
442
443 def __iter__(self):
444 return itersplitdown(self.table, self.field, self.pattern,
445 self.maxsplit, self.flags)
446
447
448 def itersplitdown(table, field, pattern, maxsplit, flags):
449
450 prog = re.compile(pattern, flags)
451 it = iter(table)
452 try:
453 hdr = next(it)
454 except StopIteration:
455 return
456 flds = list(map(text_type, hdr))
457
458 if isinstance(field, int) and field < len(hdr):
459 field_index = field
460 field = hdr[field_index]
461 elif field in flds:
462 field_index = flds.index(field)
463 else:
464 raise ArgumentError('field invalid: must be either field name or index')
465
466 yield tuple(hdr)
467
468 for row in it:
469 value = row[field_index]
470 for v in prog.split(value, maxsplit):
471 yield tuple(v if i == field_index else row[i] for i in range(len(hdr)))