annotate Lib/csv.py @ 32527:0da660e05e69 legacy-trunk

"#if WITH_THREAD" is incorrect; must be #ifdef instead; WITH_THREAD isn't always set to an integer value when it's defined.
author Tim Peters <tim.peters@gmail.com>
date Wed, 07 Jul 2004 20:42:07 +0000
parents f9dfdcb897bb
children 850f7d1e4ca2 ee808e08dd6f
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
1
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
2 """
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
3 csv.py - read/write/investigate CSV files
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
4 """
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
5
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
6 import re
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
7 from _csv import Error, __version__, writer, reader, register_dialect, \
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
8 unregister_dialect, get_dialect, list_dialects, \
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
9 QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE, \
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
10 __doc__
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
11
28828
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
12 try:
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
13 from cStringIO import StringIO
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
14 except ImportError:
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
15 from StringIO import StringIO
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
16
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
17 __all__ = [ "QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE",
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
18 "Error", "Dialect", "excel", "excel_tab", "reader", "writer",
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
19 "register_dialect", "get_dialect", "list_dialects", "Sniffer",
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
20 "unregister_dialect", "__version__", "DictReader", "DictWriter" ]
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
21
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
22 class Dialect:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
23 _name = ""
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
24 _valid = False
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
25 # placeholders
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
26 delimiter = None
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
27 quotechar = None
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
28 escapechar = None
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
29 doublequote = None
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
30 skipinitialspace = None
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
31 lineterminator = None
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
32 quoting = None
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
33
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
34 def __init__(self):
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
35 if self.__class__ != Dialect:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
36 self._valid = True
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
37 errors = self._validate()
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
38 if errors != []:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
39 raise Error, "Dialect did not validate: %s" % ", ".join(errors)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
40
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
41 def _validate(self):
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
42 errors = []
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
43 if not self._valid:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
44 errors.append("can't directly instantiate Dialect class")
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
45
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
46 if self.delimiter is None:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
47 errors.append("delimiter character not set")
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
48 elif (not isinstance(self.delimiter, str) or
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
49 len(self.delimiter) > 1):
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
50 errors.append("delimiter must be one-character string")
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
51
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
52 if self.quotechar is None:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
53 if self.quoting != QUOTE_NONE:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
54 errors.append("quotechar not set")
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
55 elif (not isinstance(self.quotechar, str) or
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
56 len(self.quotechar) > 1):
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
57 errors.append("quotechar must be one-character string")
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
58
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
59 if self.lineterminator is None:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
60 errors.append("lineterminator not set")
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
61 elif not isinstance(self.lineterminator, str):
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
62 errors.append("lineterminator must be a string")
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
63
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
64 if self.doublequote not in (True, False):
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
65 errors.append("doublequote parameter must be True or False")
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
66
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
67 if self.skipinitialspace not in (True, False):
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
68 errors.append("skipinitialspace parameter must be True or False")
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
69
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
70 if self.quoting is None:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
71 errors.append("quoting parameter not set")
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
72
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
73 if self.quoting is QUOTE_NONE:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
74 if (not isinstance(self.escapechar, (unicode, str)) or
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
75 len(self.escapechar) > 1):
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
76 errors.append("escapechar must be a one-character string or unicode object")
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
77
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
78 return errors
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
79
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
80 class excel(Dialect):
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
81 delimiter = ','
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
82 quotechar = '"'
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
83 doublequote = True
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
84 skipinitialspace = False
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
85 lineterminator = '\r\n'
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
86 quoting = QUOTE_MINIMAL
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
87 register_dialect("excel", excel)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
88
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
89 class excel_tab(excel):
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
90 delimiter = '\t'
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
91 register_dialect("excel-tab", excel_tab)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
92
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
93
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
94 class DictReader:
30632
f9dfdcb897bb Make the fieldnames argument optional in the DictReader. If self.fieldnames
Skip Montanaro <skip@pobox.com>
parents: 30356
diff changeset
95 def __init__(self, f, fieldnames=None, restkey=None, restval=None,
30356
7504812fdb7e **kwds arg was missing from __init__ for Dict{Reader,Writer} classes.
Skip Montanaro <skip@pobox.com>
parents: 30292
diff changeset
96 dialect="excel", *args, **kwds):
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
97 self.fieldnames = fieldnames # list of keys for the dict
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
98 self.restkey = restkey # key to catch long rows
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
99 self.restval = restval # default value for short rows
30356
7504812fdb7e **kwds arg was missing from __init__ for Dict{Reader,Writer} classes.
Skip Montanaro <skip@pobox.com>
parents: 30292
diff changeset
100 self.reader = reader(f, dialect, *args, **kwds)
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
101
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
102 def __iter__(self):
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
103 return self
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
104
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
105 def next(self):
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
106 row = self.reader.next()
30632
f9dfdcb897bb Make the fieldnames argument optional in the DictReader. If self.fieldnames
Skip Montanaro <skip@pobox.com>
parents: 30356
diff changeset
107 if self.fieldnames is None:
f9dfdcb897bb Make the fieldnames argument optional in the DictReader. If self.fieldnames
Skip Montanaro <skip@pobox.com>
parents: 30356
diff changeset
108 self.fieldnames = row
f9dfdcb897bb Make the fieldnames argument optional in the DictReader. If self.fieldnames
Skip Montanaro <skip@pobox.com>
parents: 30356
diff changeset
109 row = self.reader.next()
f9dfdcb897bb Make the fieldnames argument optional in the DictReader. If self.fieldnames
Skip Montanaro <skip@pobox.com>
parents: 30356
diff changeset
110
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
111 # unlike the basic reader, we prefer not to return blanks,
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
112 # because we will typically wind up with a dict full of None
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
113 # values
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
114 while row == []:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
115 row = self.reader.next()
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
116 d = dict(zip(self.fieldnames, row))
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
117 lf = len(self.fieldnames)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
118 lr = len(row)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
119 if lf < lr:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
120 d[self.restkey] = row[lf:]
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
121 elif lf > lr:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
122 for key in self.fieldnames[lr:]:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
123 d[key] = self.restval
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
124 return d
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
125
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
126
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
127 class DictWriter:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
128 def __init__(self, f, fieldnames, restval="", extrasaction="raise",
30356
7504812fdb7e **kwds arg was missing from __init__ for Dict{Reader,Writer} classes.
Skip Montanaro <skip@pobox.com>
parents: 30292
diff changeset
129 dialect="excel", *args, **kwds):
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
130 self.fieldnames = fieldnames # list of keys for the dict
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
131 self.restval = restval # for writing short dicts
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
132 if extrasaction.lower() not in ("raise", "ignore"):
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
133 raise ValueError, \
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
134 ("extrasaction (%s) must be 'raise' or 'ignore'" %
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
135 extrasaction)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
136 self.extrasaction = extrasaction
30356
7504812fdb7e **kwds arg was missing from __init__ for Dict{Reader,Writer} classes.
Skip Montanaro <skip@pobox.com>
parents: 30292
diff changeset
137 self.writer = writer(f, dialect, *args, **kwds)
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
138
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
139 def _dict_to_list(self, rowdict):
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
140 if self.extrasaction == "raise":
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
141 for k in rowdict.keys():
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
142 if k not in self.fieldnames:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
143 raise ValueError, "dict contains fields not in fieldnames"
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
144 return [rowdict.get(key, self.restval) for key in self.fieldnames]
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
145
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
146 def writerow(self, rowdict):
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
147 return self.writer.writerow(self._dict_to_list(rowdict))
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
148
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
149 def writerows(self, rowdicts):
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
150 rows = []
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
151 for rowdict in rowdicts:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
152 rows.append(self._dict_to_list(rowdict))
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
153 return self.writer.writerows(rows)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
154
29411
bac2c0e7c20a SF Patch #744104: Remove eval() from csv
Raymond Hettinger <python@rcn.com>
parents: 29169
diff changeset
155 # Guard Sniffer's type checking against builds that exclude complex()
bac2c0e7c20a SF Patch #744104: Remove eval() from csv
Raymond Hettinger <python@rcn.com>
parents: 29169
diff changeset
156 try:
bac2c0e7c20a SF Patch #744104: Remove eval() from csv
Raymond Hettinger <python@rcn.com>
parents: 29169
diff changeset
157 complex
bac2c0e7c20a SF Patch #744104: Remove eval() from csv
Raymond Hettinger <python@rcn.com>
parents: 29169
diff changeset
158 except NameError:
bac2c0e7c20a SF Patch #744104: Remove eval() from csv
Raymond Hettinger <python@rcn.com>
parents: 29169
diff changeset
159 complex = float
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
160
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
161 class Sniffer:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
162 '''
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
163 "Sniffs" the format of a CSV file (i.e. delimiter, quotechar)
28828
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
164 Returns a Dialect object.
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
165 '''
28828
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
166 def __init__(self):
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
167 # in case there is more than one possible delimiter
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
168 self.preferred = [',', '\t', ';', ' ', ':']
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
169
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
170
29169
434ef174f478 * Correct Sniffer doc to correspond to the implementation.
Skip Montanaro <skip@pobox.com>
parents: 28828
diff changeset
171 def sniff(self, sample, delimiters=None):
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
172 """
28828
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
173 Returns a dialect (or None) corresponding to the sample
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
174 """
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
175
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
176 quotechar, delimiter, skipinitialspace = \
29169
434ef174f478 * Correct Sniffer doc to correspond to the implementation.
Skip Montanaro <skip@pobox.com>
parents: 28828
diff changeset
177 self._guess_quote_and_delimiter(sample, delimiters)
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
178 if delimiter is None:
29169
434ef174f478 * Correct Sniffer doc to correspond to the implementation.
Skip Montanaro <skip@pobox.com>
parents: 28828
diff changeset
179 delimiter, skipinitialspace = self._guess_delimiter(sample,
434ef174f478 * Correct Sniffer doc to correspond to the implementation.
Skip Montanaro <skip@pobox.com>
parents: 28828
diff changeset
180 delimiters)
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
181
28828
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
182 class dialect(Dialect):
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
183 _name = "sniffed"
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
184 lineterminator = '\r\n'
28825
2fad548391de Attempt to deal with some obvious errors in the code. These were all
Fred Drake <fdrake@acm.org>
parents: 28804
diff changeset
185 quoting = QUOTE_MINIMAL
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
186 # escapechar = ''
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
187 doublequote = False
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
188
28828
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
189 dialect.delimiter = delimiter
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
190 # _csv.reader won't accept a quotechar of ''
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
191 dialect.quotechar = quotechar or '"'
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
192 dialect.skipinitialspace = skipinitialspace
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
193
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
194 return dialect
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
195
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
196
29169
434ef174f478 * Correct Sniffer doc to correspond to the implementation.
Skip Montanaro <skip@pobox.com>
parents: 28828
diff changeset
197 def _guess_quote_and_delimiter(self, data, delimiters):
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
198 """
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
199 Looks for text enclosed between two identical quotes
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
200 (the probable quotechar) which are preceded and followed
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
201 by the same character (the probable delimiter).
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
202 For example:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
203 ,'some text',
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
204 The quote with the most wins, same with the delimiter.
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
205 If there is no quotechar the delimiter can't be determined
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
206 this way.
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
207 """
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
208
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
209 matches = []
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
210 for restr in ('(?P<delim>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?P=delim)', # ,".*?",
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
211 '(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?P<delim>[^\w\n"\'])(?P<space> ?)', # ".*?",
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
212 '(?P<delim>>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?:$|\n)', # ,".*?"
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
213 '(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?:$|\n)'): # ".*?" (no delim, no space)
30292
79b1a9ec5223 use the long names for re compilation options; this makes it easier to
Fred Drake <fdrake@acm.org>
parents: 29422
diff changeset
214 regexp = re.compile(restr, re.DOTALL | re.MULTILINE)
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
215 matches = regexp.findall(data)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
216 if matches:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
217 break
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
218
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
219 if not matches:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
220 return ('', None, 0) # (quotechar, delimiter, skipinitialspace)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
221
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
222 quotes = {}
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
223 delims = {}
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
224 spaces = 0
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
225 for m in matches:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
226 n = regexp.groupindex['quote'] - 1
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
227 key = m[n]
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
228 if key:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
229 quotes[key] = quotes.get(key, 0) + 1
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
230 try:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
231 n = regexp.groupindex['delim'] - 1
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
232 key = m[n]
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
233 except KeyError:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
234 continue
29169
434ef174f478 * Correct Sniffer doc to correspond to the implementation.
Skip Montanaro <skip@pobox.com>
parents: 28828
diff changeset
235 if key and (delimiters is None or key in delimiters):
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
236 delims[key] = delims.get(key, 0) + 1
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
237 try:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
238 n = regexp.groupindex['space'] - 1
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
239 except KeyError:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
240 continue
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
241 if m[n]:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
242 spaces += 1
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
243
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
244 quotechar = reduce(lambda a, b, quotes = quotes:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
245 (quotes[a] > quotes[b]) and a or b, quotes.keys())
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
246
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
247 if delims:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
248 delim = reduce(lambda a, b, delims = delims:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
249 (delims[a] > delims[b]) and a or b, delims.keys())
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
250 skipinitialspace = delims[delim] == spaces
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
251 if delim == '\n': # most likely a file with a single column
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
252 delim = ''
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
253 else:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
254 # there is *no* delimiter, it's a single column of quoted data
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
255 delim = ''
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
256 skipinitialspace = 0
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
257
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
258 return (quotechar, delim, skipinitialspace)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
259
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
260
29169
434ef174f478 * Correct Sniffer doc to correspond to the implementation.
Skip Montanaro <skip@pobox.com>
parents: 28828
diff changeset
261 def _guess_delimiter(self, data, delimiters):
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
262 """
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
263 The delimiter /should/ occur the same number of times on
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
264 each row. However, due to malformed data, it may not. We don't want
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
265 an all or nothing approach, so we allow for small variations in this
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
266 number.
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
267 1) build a table of the frequency of each character on every line.
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
268 2) build a table of freqencies of this frequency (meta-frequency?),
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
269 e.g. 'x occurred 5 times in 10 rows, 6 times in 1000 rows,
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
270 7 times in 2 rows'
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
271 3) use the mode of the meta-frequency to determine the /expected/
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
272 frequency for that character
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
273 4) find out how often the character actually meets that goal
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
274 5) the character that best meets its goal is the delimiter
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
275 For performance reasons, the data is evaluated in chunks, so it can
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
276 try and evaluate the smallest portion of the data possible, evaluating
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
277 additional chunks as necessary.
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
278 """
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
279
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
280 data = filter(None, data.split('\n'))
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
281
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
282 ascii = [chr(c) for c in range(127)] # 7-bit ASCII
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
283
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
284 # build frequency tables
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
285 chunkLength = min(10, len(data))
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
286 iteration = 0
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
287 charFrequency = {}
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
288 modes = {}
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
289 delims = {}
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
290 start, end = 0, min(chunkLength, len(data))
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
291 while start < len(data):
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
292 iteration += 1
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
293 for line in data[start:end]:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
294 for char in ascii:
28828
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
295 metaFrequency = charFrequency.get(char, {})
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
296 # must count even if frequency is 0
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
297 freq = line.strip().count(char)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
298 # value is the mode
28828
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
299 metaFrequency[freq] = metaFrequency.get(freq, 0) + 1
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
300 charFrequency[char] = metaFrequency
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
301
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
302 for char in charFrequency.keys():
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
303 items = charFrequency[char].items()
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
304 if len(items) == 1 and items[0][0] == 0:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
305 continue
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
306 # get the mode of the frequencies
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
307 if len(items) > 1:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
308 modes[char] = reduce(lambda a, b: a[1] > b[1] and a or b,
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
309 items)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
310 # adjust the mode - subtract the sum of all
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
311 # other frequencies
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
312 items.remove(modes[char])
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
313 modes[char] = (modes[char][0], modes[char][1]
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
314 - reduce(lambda a, b: (0, a[1] + b[1]),
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
315 items)[1])
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
316 else:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
317 modes[char] = items[0]
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
318
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
319 # build a list of possible delimiters
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
320 modeList = modes.items()
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
321 total = float(chunkLength * iteration)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
322 # (rows of consistent data) / (number of rows) = 100%
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
323 consistency = 1.0
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
324 # minimum consistency threshold
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
325 threshold = 0.9
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
326 while len(delims) == 0 and consistency >= threshold:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
327 for k, v in modeList:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
328 if v[0] > 0 and v[1] > 0:
29169
434ef174f478 * Correct Sniffer doc to correspond to the implementation.
Skip Montanaro <skip@pobox.com>
parents: 28828
diff changeset
329 if ((v[1]/total) >= consistency and
434ef174f478 * Correct Sniffer doc to correspond to the implementation.
Skip Montanaro <skip@pobox.com>
parents: 28828
diff changeset
330 (delimiters is None or k in delimiters)):
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
331 delims[k] = v
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
332 consistency -= 0.01
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
333
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
334 if len(delims) == 1:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
335 delim = delims.keys()[0]
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
336 skipinitialspace = (data[0].count(delim) ==
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
337 data[0].count("%c " % delim))
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
338 return (delim, skipinitialspace)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
339
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
340 # analyze another chunkLength lines
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
341 start = end
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
342 end += chunkLength
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
343
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
344 if not delims:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
345 return ('', 0)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
346
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
347 # if there's more than one, fall back to a 'preferred' list
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
348 if len(delims) > 1:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
349 for d in self.preferred:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
350 if d in delims.keys():
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
351 skipinitialspace = (data[0].count(d) ==
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
352 data[0].count("%c " % d))
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
353 return (d, skipinitialspace)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
354
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
355 # finally, just return the first damn character in the list
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
356 delim = delims.keys()[0]
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
357 skipinitialspace = (data[0].count(delim) ==
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
358 data[0].count("%c " % delim))
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
359 return (delim, skipinitialspace)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
360
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
361
28828
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
362 def has_header(self, sample):
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
363 # Creates a dictionary of types of data in each column. If any
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
364 # column is of a single type (say, integers), *except* for the first
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
365 # row, then the first row is presumed to be labels. If the type
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
366 # can't be determined, it is assumed to be a string in which case
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
367 # the length of the string is the determining factor: if all of the
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
368 # rows except for the first are the same length, it's a header.
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
369 # Finally, a 'vote' is taken at the end for each column, adding or
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
370 # subtracting from the likelihood of the first row being a header.
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
371
28828
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
372 rdr = reader(StringIO(sample), self.sniff(sample))
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
373
28828
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
374 header = rdr.next() # assume first row is header
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
375
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
376 columns = len(header)
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
377 columnTypes = {}
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
378 for i in range(columns): columnTypes[i] = None
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
379
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
380 checked = 0
28828
b37af21b77be rework Sniffer api significantly
Skip Montanaro <skip@pobox.com>
parents: 28825
diff changeset
381 for row in rdr:
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
382 # arbitrary number of rows to check, to keep it sane
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
383 if checked > 20:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
384 break
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
385 checked += 1
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
386
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
387 if len(row) != columns:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
388 continue # skip rows that have irregular number of columns
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
389
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
390 for col in columnTypes.keys():
29411
bac2c0e7c20a SF Patch #744104: Remove eval() from csv
Raymond Hettinger <python@rcn.com>
parents: 29169
diff changeset
391
bac2c0e7c20a SF Patch #744104: Remove eval() from csv
Raymond Hettinger <python@rcn.com>
parents: 29169
diff changeset
392 for thisType in [int, long, float, complex]:
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
393 try:
29411
bac2c0e7c20a SF Patch #744104: Remove eval() from csv
Raymond Hettinger <python@rcn.com>
parents: 29169
diff changeset
394 thisType(row[col])
bac2c0e7c20a SF Patch #744104: Remove eval() from csv
Raymond Hettinger <python@rcn.com>
parents: 29169
diff changeset
395 break
29420
f87fcd0870bf The multiple exception catch should be in a tuple.
Raymond Hettinger <python@rcn.com>
parents: 29411
diff changeset
396 except (ValueError, OverflowError):
29411
bac2c0e7c20a SF Patch #744104: Remove eval() from csv
Raymond Hettinger <python@rcn.com>
parents: 29169
diff changeset
397 pass
bac2c0e7c20a SF Patch #744104: Remove eval() from csv
Raymond Hettinger <python@rcn.com>
parents: 29169
diff changeset
398 else:
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
399 # fallback to length of string
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
400 thisType = len(row[col])
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
401
29411
bac2c0e7c20a SF Patch #744104: Remove eval() from csv
Raymond Hettinger <python@rcn.com>
parents: 29169
diff changeset
402 # treat longs as ints
bac2c0e7c20a SF Patch #744104: Remove eval() from csv
Raymond Hettinger <python@rcn.com>
parents: 29169
diff changeset
403 if thisType == long:
bac2c0e7c20a SF Patch #744104: Remove eval() from csv
Raymond Hettinger <python@rcn.com>
parents: 29169
diff changeset
404 thisType = int
bac2c0e7c20a SF Patch #744104: Remove eval() from csv
Raymond Hettinger <python@rcn.com>
parents: 29169
diff changeset
405
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
406 if thisType != columnTypes[col]:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
407 if columnTypes[col] is None: # add new column type
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
408 columnTypes[col] = thisType
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
409 else:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
410 # type is inconsistent, remove column from
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
411 # consideration
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
412 del columnTypes[col]
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
413
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
414 # finally, compare results against first row and "vote"
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
415 # on whether it's a header
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
416 hasHeader = 0
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
417 for col, colType in columnTypes.items():
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
418 if type(colType) == type(0): # it's a length
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
419 if len(header[col]) != colType:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
420 hasHeader += 1
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
421 else:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
422 hasHeader -= 1
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
423 else: # attempt typecast
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
424 try:
29411
bac2c0e7c20a SF Patch #744104: Remove eval() from csv
Raymond Hettinger <python@rcn.com>
parents: 29169
diff changeset
425 colType(header[col])
29422
cf8ae3b0dcdc One more multiple exception catch should be in a tuple.
Raymond Hettinger <python@rcn.com>
parents: 29420
diff changeset
426 except (ValueError, TypeError):
28804
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
427 hasHeader += 1
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
428 else:
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
429 hasHeader -= 1
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
430
0c950e3323ee cvs is going to be a module again
Skip Montanaro <skip@pobox.com>
parents:
diff changeset
431 return hasHeader > 0