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