| 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 |
|
| 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 |
|
| 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 |
| 84 |
self.restkey = restkey |
| 85 |
self.restval = restval |
| 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 |
|
| 110 |
self.fieldnames |
| 111 |
row = next(self.reader) |
| 112 |
self.line_num = self.reader.line_num |
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 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 |
| 134 |
self.restval = restval |
| 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 |
|
| 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)')] |
| 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 |
|
| 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 |
|
| 200 |
|
| 201 |
dialect.doublequote = doublequote |
| 202 |
dialect.delimiter = delimiter |
| 203 |
|
| 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 |
|
| 224 |
|
| 225 |
for regexp in _SNIFFER_RES: |
| 226 |
matches = regexp.findall(data) |
| 227 |
if matches: |
| 228 |
break |
| 229 |
|
| 230 |
if not matches: |
| 231 |
|
| 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': |
| 262 |
delim = '' |
| 263 |
else: |
| 264 |
|
| 265 |
delim = '' |
| 266 |
skipinitialspace = 0 |
| 267 |
|
| 268 |
|
| 269 |
|
| 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)] |
| 306 |
|
| 307 |
|
| 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 |
|
| 320 |
freq = line.count(char) |
| 321 |
|
| 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 |
|
| 330 |
if len(items) > 1: |
| 331 |
modes[char] = max(items, key=lambda x: x[1]) |
| 332 |
|
| 333 |
|
| 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 |
|
| 341 |
modeList = modes.items() |
| 342 |
total = float(min(chunkLength * iteration, len(data))) |
| 343 |
|
| 344 |
consistency = 1.0 |
| 345 |
|
| 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 |
|
| 362 |
start = end |
| 363 |
end += chunkLength |
| 364 |
|
| 365 |
if not delims: |
| 366 |
return ('', 0) |
| 367 |
|
| 368 |
|
| 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 |
|
| 377 |
|
| 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 |
|
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
|
| 393 |
|
| 394 |
|
| 395 |
|
| 396 |
|
| 397 |
rdr = reader(StringIO(sample), self.sniff(sample)) |
| 398 |
|
| 399 |
header = next(rdr) |
| 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 |
|
| 408 |
if checked > 20: |
| 409 |
break |
| 410 |
checked += 1 |
| 411 |
|
| 412 |
if len(row) != columns: |
| 413 |
continue |
| 414 |
|
| 415 |
for col in list(columnTypes.keys()): |
| 416 |
thisType = complex |
| 417 |
try: |
| 418 |
thisType(row[col]) |
| 419 |
except (ValueError, OverflowError): |
| 420 |
|
| 421 |
thisType = len(row[col]) |
| 422 |
|
| 423 |
if thisType != columnTypes[col]: |
| 424 |
if columnTypes[col] is None: |
| 425 |
columnTypes[col] = thisType |
| 426 |
else: |
| 427 |
|
| 428 |
|
| 429 |
del columnTypes[col] |
| 430 |
|
| 431 |
|
| 432 |
|
| 433 |
hasHeader = 0 |
| 434 |
for col, colType in columnTypes.items(): |
| 435 |
if type(colType) == type(0): |
| 436 |
if len(header[col]) != colType: |
| 437 |
hasHeader += 1 |
| 438 |
else: |
| 439 |
hasHeader -= 1 |
| 440 |
else: |
| 441 |
try: |
| 442 |
colType(header[col]) |
| 443 |
except (ValueError, TypeError): |
| 444 |
hasHeader += 1 |
| 445 |
else: |
| 446 |
hasHeader -= 1 |
| 447 |
|
| 448 |
return hasHeader > 0 |