Debian Codegraph @

lib-python/3/csv.py

raw symbols SCIP
1
2 """
3 csv.py - read/write/investigate CSV files
4 """
5
6 import re
7 from _csv import Error, __version__, writer, reader, register_dialect, \
8 unregister_dialect, get_dialect, list_dialects, \
9 field_size_limit, \
10 QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE, \
11 __doc__
12 from _csv import Dialect as _Dialect
13
14 from io import StringIO
15
16 __all__ = ["QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE",
17 "Error", "Dialect", "__doc__", "excel", "excel_tab",
18 "field_size_limit", "reader", "writer",
19 "register_dialect", "get_dialect", "list_dialects", "Sniffer",
20 "unregister_dialect", "__version__", "DictReader", "DictWriter",
21 "unix_dialect"]
22
23 class Dialect:
24 """Describe a CSV dialect.
25
26 This must be subclassed (see csv.excel). Valid attributes are:
27 delimiter, quotechar, escapechar, doublequote, skipinitialspace,
28 lineterminator, quoting.
29
30 """
31 _name = ""
32 _valid = False
33 # placeholders
34 delimiter = None
35 quotechar = None
36 escapechar = None
37 doublequote = None
38 skipinitialspace = None
39 lineterminator = None
40 quoting = None
41
42 def __init__(self):
43 if self.__class__ != Dialect:
44 self._valid = True
45 self._validate()
46
47 def _validate(self):
48 try:
49 _Dialect(self)
50 except TypeError as e:
51 # We do this for compatibility with py2.3
52 raise Error(str(e))
53
54 class excel(Dialect):
55 """Describe the usual properties of Excel-generated CSV files."""
56 delimiter = ','
57 quotechar = '"'
58 doublequote = True
59 skipinitialspace = False
60 lineterminator = '\r\n'
61 quoting = QUOTE_MINIMAL
62 register_dialect("excel", excel)
63
64 class excel_tab(excel):
65 """Describe the usual properties of Excel-generated TAB-delimited files."""
66 delimiter = '\t'
67 register_dialect("excel-tab", excel_tab)
68
69 class unix_dialect(Dialect):
70 """Describe the usual properties of Unix-generated CSV files."""
71 delimiter = ','
72 quotechar = '"'
73 doublequote = True
74 skipinitialspace = False
75 lineterminator = '\n'
76 quoting = QUOTE_ALL
77 register_dialect("unix", unix_dialect)
78
79
80 class DictReader:
81 def __init__(self, f, fieldnames=None, restkey=None, restval=None,
82 dialect="excel", *args, **kwds):
83 self._fieldnames = fieldnames # list of keys for the dict
84 self.restkey = restkey # key to catch long rows
85 self.restval = restval # default value for short rows
86 self.reader = reader(f, dialect, *args, **kwds)
87 self.dialect = dialect
88 self.line_num = 0
89
90 def __iter__(self):
91 return self
92
93 @property
94 def fieldnames(self):
95 if self._fieldnames is None:
96 try:
97 self._fieldnames = next(self.reader)
98 except StopIteration:
99 pass
100 self.line_num = self.reader.line_num
101 return self._fieldnames
102
103 @fieldnames.setter
104 def fieldnames(self, value):
105 self._fieldnames = value
106
107 def __next__(self):
108 if self.line_num == 0:
109 # Used only for its side effect.
110 self.fieldnames
111 row = next(self.reader)
112 self.line_num = self.reader.line_num
113
114 # unlike the basic reader, we prefer not to return blanks,
115 # because we will typically wind up with a dict full of None
116 # values
117 while row == []:
118 row = next(self.reader)
119 d = dict(zip(self.fieldnames, row))
120 lf = len(self.fieldnames)
121 lr = len(row)
122 if lf < lr:
123 d[self.restkey] = row[lf:]
124 elif lf > lr:
125 for key in self.fieldnames[lr:]:
126 d[key] = self.restval
127 return d
128
129
130 class DictWriter:
131 def __init__(self, f, fieldnames, restval="", extrasaction="raise",
132 dialect="excel", *args, **kwds):
133 self.fieldnames = fieldnames # list of keys for the dict
134 self.restval = restval # for writing short dicts
135 if extrasaction.lower() not in ("raise", "ignore"):
136 raise ValueError("extrasaction (%s) must be 'raise' or 'ignore'"
137 % extrasaction)
138 self.extrasaction = extrasaction
139 self.writer = writer(f, dialect, *args, **kwds)
140
141 def writeheader(self):
142 header = dict(zip(self.fieldnames, self.fieldnames))
143 return self.writerow(header)
144
145 def _dict_to_list(self, rowdict):
146 if self.extrasaction == "raise":
147 wrong_fields = rowdict.keys() - self.fieldnames
148 if wrong_fields:
149 raise ValueError("dict contains fields not in fieldnames: "
150 + ", ".join([repr(x) for x in wrong_fields]))
151 return (rowdict.get(key, self.restval) for key in self.fieldnames)
152
153 def writerow(self, rowdict):
154 return self.writer.writerow(self._dict_to_list(rowdict))
155
156 def writerows(self, rowdicts):
157 return self.writer.writerows(map(self._dict_to_list, rowdicts))
158
159 # Guard Sniffer's type checking against builds that exclude complex()
160 try:
161 complex
162 except NameError:
163 complex = float
164
165 _SNIFFER_RES = [re.compile(restr, re.DOTALL | re.MULTILINE) for restr in
166 (r'(?P<delim>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?P=delim)', # ,".*?",
167 r'(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?P<delim>[^\w\n"\'])(?P<space> ?)', # ".*?",
168 r'(?P<delim>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?:$|\n)', # ,".*?"
169 r'(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?:$|\n)')] # ".*?" (no delim, no space)
170
171 class Sniffer:
172 '''
173 "Sniffs" the format of a CSV file (i.e. delimiter, quotechar)
174 Returns a Dialect object.
175 '''
176 def __init__(self):
177 # in case there is more than one possible delimiter
178 self.preferred = [',', '\t', ';', ' ', ':']
179
180
181 def sniff(self, sample, delimiters=None):
182 """
183 Returns a dialect (or None) corresponding to the sample
184 """
185
186 quotechar, doublequote, delimiter, skipinitialspace = \
187 self._guess_quote_and_delimiter(sample, delimiters)
188 if not delimiter:
189 delimiter, skipinitialspace = self._guess_delimiter(sample,
190 delimiters)
191
192 if not delimiter:
193 raise Error("Could not determine delimiter")
194
195 class dialect(Dialect):
196 _name = "sniffed"
197 lineterminator = '\r\n'
198 quoting = QUOTE_MINIMAL
199 # escapechar = ''
200
201 dialect.doublequote = doublequote
202 dialect.delimiter = delimiter
203 # _csv.reader won't accept a quotechar of ''
204 dialect.quotechar = quotechar or '"'
205 dialect.skipinitialspace = skipinitialspace
206
207 return dialect
208
209
210 def _guess_quote_and_delimiter(self, data, delimiters):
211 """
212 Looks for text enclosed between two identical quotes
213 (the probable quotechar) which are preceded and followed
214 by the same character (the probable delimiter).
215 For example:
216 ,'some text',
217 The quote with the most wins, same with the delimiter.
218 If there is no quotechar the delimiter can't be determined
219 this way.
220 """
221
222 matches = []
223 # PyPy difference: compile the regular expressions only once, globally,
224 # instead of on every call to sniff
225 for regexp in _SNIFFER_RES:
226 matches = regexp.findall(data)
227 if matches:
228 break
229
230 if not matches:
231 # (quotechar, doublequote, delimiter, skipinitialspace)
232 return ('', False, None, 0)
233 quotes = {}
234 delims = {}
235 spaces = 0
236 groupindex = regexp.groupindex
237 for m in matches:
238 n = groupindex['quote'] - 1
239 key = m[n]
240 if key:
241 quotes[key] = quotes.get(key, 0) + 1
242 try:
243 n = groupindex['delim'] - 1
244 key = m[n]
245 except KeyError:
246 continue
247 if key and (delimiters is None or key in delimiters):
248 delims[key] = delims.get(key, 0) + 1
249 try:
250 n = groupindex['space'] - 1
251 except KeyError:
252 continue
253 if m[n]:
254 spaces += 1
255
256 quotechar = max(quotes, key=quotes.get)
257
258 if delims:
259 delim = max(delims, key=delims.get)
260 skipinitialspace = delims[delim] == spaces
261 if delim == '\n': # most likely a file with a single column
262 delim = ''
263 else:
264 # there is *no* delimiter, it's a single column of quoted data
265 delim = ''
266 skipinitialspace = 0
267
268 # if we see an extra quote between delimiters, we've got a
269 # double quoted format
270 dq_regexp = re.compile(
271 r"((%(delim)s)|^)\W*%(quote)s[^%(delim)s\n]*%(quote)s[^%(delim)s\n]*%(quote)s\W*((%(delim)s)|$)" % \
272 {'delim':re.escape(delim), 'quote':quotechar}, re.MULTILINE)
273
274
275
276 if dq_regexp.search(data):
277 doublequote = True
278 else:
279 doublequote = False
280
281 return (quotechar, doublequote, delim, skipinitialspace)
282
283
284 def _guess_delimiter(self, data, delimiters):
285 """
286 The delimiter /should/ occur the same number of times on
287 each row. However, due to malformed data, it may not. We don't want
288 an all or nothing approach, so we allow for small variations in this
289 number.
290 1) build a table of the frequency of each character on every line.
291 2) build a table of frequencies of this frequency (meta-frequency?),
292 e.g. 'x occurred 5 times in 10 rows, 6 times in 1000 rows,
293 7 times in 2 rows'
294 3) use the mode of the meta-frequency to determine the /expected/
295 frequency for that character
296 4) find out how often the character actually meets that goal
297 5) the character that best meets its goal is the delimiter
298 For performance reasons, the data is evaluated in chunks, so it can
299 try and evaluate the smallest portion of the data possible, evaluating
300 additional chunks as necessary.
301 """
302
303 data = list(filter(None, data.split('\n')))
304
305 ascii = [chr(c) for c in range(127)] # 7-bit ASCII
306
307 # build frequency tables
308 chunkLength = min(10, len(data))
309 iteration = 0
310 charFrequency = {}
311 modes = {}
312 delims = {}
313 start, end = 0, chunkLength
314 while start < len(data):
315 iteration += 1
316 for line in data[start:end]:
317 for char in ascii:
318 metaFrequency = charFrequency.get(char, {})
319 # must count even if frequency is 0
320 freq = line.count(char)
321 # value is the mode
322 metaFrequency[freq] = metaFrequency.get(freq, 0) + 1
323 charFrequency[char] = metaFrequency
324
325 for char in charFrequency.keys():
326 items = list(charFrequency[char].items())
327 if len(items) == 1 and items[0][0] == 0:
328 continue
329 # get the mode of the frequencies
330 if len(items) > 1:
331 modes[char] = max(items, key=lambda x: x[1])
332 # adjust the mode - subtract the sum of all
333 # other frequencies
334 items.remove(modes[char])
335 modes[char] = (modes[char][0], modes[char][1]
336 - sum(item[1] for item in items))
337 else:
338 modes[char] = items[0]
339
340 # build a list of possible delimiters
341 modeList = modes.items()
342 total = float(min(chunkLength * iteration, len(data)))
343 # (rows of consistent data) / (number of rows) = 100%
344 consistency = 1.0
345 # minimum consistency threshold
346 threshold = 0.9
347 while len(delims) == 0 and consistency >= threshold:
348 for k, v in modeList:
349 if v[0] > 0 and v[1] > 0:
350 if ((v[1]/total) >= consistency and
351 (delimiters is None or k in delimiters)):
352 delims[k] = v
353 consistency -= 0.01
354
355 if len(delims) == 1:
356 delim = list(delims.keys())[0]
357 skipinitialspace = (data[0].count(delim) ==
358 data[0].count("%c " % delim))
359 return (delim, skipinitialspace)
360
361 # analyze another chunkLength lines
362 start = end
363 end += chunkLength
364
365 if not delims:
366 return ('', 0)
367
368 # if there's more than one, fall back to a 'preferred' list
369 if len(delims) > 1:
370 for d in self.preferred:
371 if d in delims.keys():
372 skipinitialspace = (data[0].count(d) ==
373 data[0].count("%c " % d))
374 return (d, skipinitialspace)
375
376 # nothing else indicates a preference, pick the character that
377 # dominates(?)
378 items = [(v,k) for (k,v) in delims.items()]
379 items.sort()
380 delim = items[-1][1]
381
382 skipinitialspace = (data[0].count(delim) ==
383 data[0].count("%c " % delim))
384 return (delim, skipinitialspace)
385
386
387 def has_header(self, sample):
388 # Creates a dictionary of types of data in each column. If any
389 # column is of a single type (say, integers), *except* for the first
390 # row, then the first row is presumed to be labels. If the type
391 # can't be determined, it is assumed to be a string in which case
392 # the length of the string is the determining factor: if all of the
393 # rows except for the first are the same length, it's a header.
394 # Finally, a 'vote' is taken at the end for each column, adding or
395 # subtracting from the likelihood of the first row being a header.
396
397 rdr = reader(StringIO(sample), self.sniff(sample))
398
399 header = next(rdr) # assume first row is header
400
401 columns = len(header)
402 columnTypes = {}
403 for i in range(columns): columnTypes[i] = None
404
405 checked = 0
406 for row in rdr:
407 # arbitrary number of rows to check, to keep it sane
408 if checked > 20:
409 break
410 checked += 1
411
412 if len(row) != columns:
413 continue # skip rows that have irregular number of columns
414
415 for col in list(columnTypes.keys()):
416 thisType = complex
417 try:
418 thisType(row[col])
419 except (ValueError, OverflowError):
420 # fallback to length of string
421 thisType = len(row[col])
422
423 if thisType != columnTypes[col]:
424 if columnTypes[col] is None: # add new column type
425 columnTypes[col] = thisType
426 else:
427 # type is inconsistent, remove column from
428 # consideration
429 del columnTypes[col]
430
431 # finally, compare results against first row and "vote"
432 # on whether it's a header
433 hasHeader = 0
434 for col, colType in columnTypes.items():
435 if type(colType) == type(0): # it's a length
436 if len(header[col]) != colType:
437 hasHeader += 1
438 else:
439 hasHeader -= 1
440 else: # attempt typecast
441 try:
442 colType(header[col])
443 except (ValueError, TypeError):
444 hasHeader += 1
445 else:
446 hasHeader -= 1
447
448 return hasHeader > 0