Debian Codegraph @

clevercsv/detect.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 """
4 Drop-in replacement for Python Sniffer object.
5
6 Author: Gertjan van den Burg
7
8 """
9
10 from enum import Enum
11 from io import StringIO
12
13 from typing import Dict
14 from typing import Iterable
15 from typing import Optional
16 from typing import Union
17
18 from .consistency import ConsistencyDetector
19 from .dialect import SimpleDialect
20 from .exceptions import NoDetectionResult
21 from .normal_form import detect_dialect_normal
22 from .read import reader
23
24
25 class DetectionMethod(str, Enum):
26 """Possible detection methods
27
28 Valid options are `"auto"` (the default for :class:`Detector.detect`),
29 `"normal"`, or `"consistency"`. The `"auto"` option first attempts to
30 detect the dialect using normal-form detection, and uses the consistency
31 measure if normal-form detection is inconclusive. The `"normal"` method
32 uses normal-form detection excllusively, and the `"consistency"` method
33 uses the consistency measure exclusively.
34 """
35
36 AUTO = "auto"
37 NORMAL = "normal"
38 CONSISTENCY = "consistency"
39
40
41 class Detector:
42 """
43 Detect the Dialect of CSV files with normal forms or the data consistency
44 measure. This class provides a drop-in replacement for the Python dialect
45 Sniffer from the standard library.
46
47 Note
48 ----
49 We call the object ``Detector`` just to mark the difference in the
50 implementation and avoid naming issues. You can import it as ``from ccsv
51 import Sniffer`` nonetheless.
52
53 """
54
55 def sniff(
56 self,
57 sample: str,
58 delimiters: Optional[Iterable[str]] = None,
59 verbose: bool = False,
60 ) -> Optional[SimpleDialect]:
61 # Compatibility method for Python
62 return self.detect(sample, delimiters=delimiters, verbose=verbose)
63
64 def detect(
65 self,
66 sample: str,
67 delimiters: Optional[Iterable[str]] = None,
68 verbose: bool = False,
69 method: Union[DetectionMethod, str] = DetectionMethod.AUTO,
70 skip: bool = True,
71 ) -> Optional[SimpleDialect]:
72 """Detect the dialect of a CSV file
73
74 This method detects the dialect of the CSV file using the specified
75 detection method.
76
77 Parameters
78 ----------
79 sample : str
80 A sample of text from the CSV file. For best results and if time
81 allows, use the entire contents of the CSV file as the sample.
82
83 delimiters : Optional[Iterable[str]]
84 Set of delimiters to consider for dialect detection. The potential
85 dialects will be constructed by analyzing the sample and these
86 delimiters. If omitted, the set of potential delimiters will be
87 constructed from the sample.
88
89 verbose : bool
90 Enable verbose mode.
91
92 method : Union[DetectionMethod, str]
93 The method to use for dialect detection. Possible values are
94 :class:`DetectionMethod` instances or strings that can be cast to
95 as such an enum.
96
97 skip : bool
98 Whether to skip potential dialects that have too low a pattern
99 score in the consistency detection. See
100 :func:`ConsistencyDetector.compute_consistency_scores` for more
101 details.
102
103 Returns
104 -------
105 dialect : Optional[SimpleDialect]
106 The detected dialect. Can be `None` if dialect detection was
107 inconclusive.
108
109 """
110 method = DetectionMethod(method) if isinstance(method, str) else method
111 if delimiters is not None:
112 delimiters = list(delimiters)
113 if method == DetectionMethod.NORMAL or method == DetectionMethod.AUTO:
114 if verbose:
115 print("Running normal form detection ...", flush=True)
116 dialect = detect_dialect_normal(
117 sample, delimiters=delimiters, verbose=verbose
118 )
119 if dialect is not None:
120 self.method_ = DetectionMethod.NORMAL
121 return dialect
122
123 self.method_ = DetectionMethod.CONSISTENCY
124 consistency_detector = ConsistencyDetector(skip=skip, verbose=verbose)
125 if verbose:
126 print("Running data consistency measure ...", flush=True)
127 return consistency_detector.detect(sample, delimiters=delimiters)
128
129 def has_header(self, sample: str, max_rows_to_check: int = 20) -> bool:
130 """Detect if a file has a header from a sample.
131
132 This function is copied from CPython! The only change we've made is to
133 use our dialect detection method.
134
135 """
136
137 # Creates a dictionary of types of data in each column. If any
138 # column is of a single type (say, integers), *except* for the first
139 # row, then the first row is presumed to be labels. If the type
140 # can't be determined, it is assumed to be a string in which case
141 # the length of the string is the determining factor: if all of the
142 # rows except for the first are the same length, it's a header.
143 # Finally, a 'vote' is taken at the end for each column, adding or
144 # subtracting from the likelihood of the first row being a header.
145
146 dialect = self.sniff(sample)
147 if dialect is None:
148 raise NoDetectionResult
149
150 rdr = reader(StringIO(sample), dialect)
151
152 header = next(rdr) # assume first row is header
153
154 columns = len(header)
155 columnTypes: Dict[int, Optional[Union[int, type]]] = {}
156 for i in range(columns):
157 columnTypes[i] = None
158
159 thisType: Union[int, type]
160 checked = 0
161 for row in rdr:
162 # arbitrary number of rows to check, to keep it sane
163 if checked > max_rows_to_check:
164 break
165 checked += 1
166
167 if len(row) != columns:
168 continue # skip rows that have irregular number of columns
169
170 for col in list(columnTypes.keys()):
171 for thisType in [int, float, complex]:
172 try:
173 thisType(row[col])
174 break
175 except (ValueError, OverflowError):
176 pass
177 else:
178 # fallback to length of string
179 thisType = len(row[col])
180
181 if thisType != columnTypes[col]:
182 if columnTypes[col] is None: # add new column type
183 columnTypes[col] = thisType
184 else:
185 # type is inconsistent, remove column from
186 # consideration
187 del columnTypes[col]
188
189 # finally, compare results against first row and "vote"
190 # on whether it's a header
191 hasHeader = 0
192 for col, colType in columnTypes.items():
193 if isinstance(colType, int): # it's a length
194 if len(header[col]) != colType:
195 hasHeader += 1
196 else:
197 hasHeader -= 1
198 else: # attempt typecast
199 if colType is None:
200 hasHeader += 1
201 continue
202
203 try:
204 colType(header[col])
205 except (ValueError, TypeError):
206 hasHeader += 1
207 else:
208 hasHeader -= 1
209
210 return hasHeader > 0