Skip to content

gh-137627: Make csv.Sniffer.sniff() delimiter detection 1.5x faster #137628

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Doc/whatsnew/3.15.rst
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,13 @@ New modules
Improved modules
================

csv
---

* The :meth:`csv.Sniffer.sniff` delimiter detection has been optimized,
and is now up to 1.5x faster.
(Contributed by Maurycy Pawłowski-Wieroński in :gh:`137628`.)

dbm
---

Expand Down
30 changes: 17 additions & 13 deletions Lib/csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,31 +364,35 @@ def _guess_delimiter(self, data, delimiters):
try and evaluate the smallest portion of the data possible, evaluating
additional chunks as necessary.
"""
from collections import Counter, defaultdict

data = list(filter(None, data.split('\n')))

ascii = [chr(c) for c in range(127)] # 7-bit ASCII

# build frequency tables
chunkLength = min(10, len(data))
iteration = 0
charFrequency = {}
seen = 0
# {char -> {count_per_line -> num_lines_with_that_count}}
charFrequency = defaultdict(Counter)
modes = {}
delims = {}
start, end = 0, chunkLength
while start < len(data):
iteration += 1
for line in data[start:end]:
for char in ascii:
metaFrequency = charFrequency.get(char, {})
# must count even if frequency is 0
freq = line.count(char)
# value is the mode
metaFrequency[freq] = metaFrequency.get(freq, 0) + 1
charFrequency[char] = metaFrequency

for char in charFrequency.keys():
items = list(charFrequency[char].items())
seen += 1
charCounts = Counter(line)
for char, count in charCounts.items():
if ord(char) < 127:
charFrequency[char][count] += 1

for char, counts in charFrequency.items():
presentCount = sum(counts.values())
zeroCount = seen - presentCount
if zeroCount > 0:
items = list(counts.items()) + [(0, zeroCount)]
else:
items = list(counts.items())
if len(items) == 1 and items[0][0] == 0:
continue
# get the mode of the frequencies
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Speed up :meth:`csv.Sniffer.sniff` delimiter detection by up to 1.5x.
Loading