File size: 2,245 Bytes
b199558
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env bash
# Oracle solution: csv module for RFC4180, Decimal for exact numeric rewriting.
set -euo pipefail
cd "$TB_WORK"
mkdir -p bin

cat > bin/canon <<'PYEOF'
#!/usr/bin/env python3
import csv
import re
import sys
from decimal import Decimal, InvalidOperation
from pathlib import Path

NUMERIC = re.compile(r"^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$")


def normalize(cell):
    if not NUMERIC.match(cell):
        return cell
    try:
        value = Decimal(cell)
    except InvalidOperation:
        return cell
    if value == 0:
        return "0"
    return format(value.normalize(), "f")


def main(argv):
    if len(argv) != 3:
        sys.stderr.write("usage: canon <input.csv> <output.tsv>\n")
        return 1
    source = Path(argv[1])
    target = Path(argv[2])
    if not source.is_file():
        sys.stderr.write("no such file: %s\n" % argv[1])
        return 2

    with open(source, "r", encoding="utf-8-sig", newline="") as handle:
        reader = csv.reader(handle)
        header = next(reader, None)
        if header is None:
            header = []
        header = [name.strip() for name in header]

        seen = set()
        for name in header:
            key = name.casefold()
            if key in seen:
                sys.stderr.write("duplicate column: %s\n" % name)
                return 3
            seen.add(key)

        rows = []
        previous_line = reader.line_num
        for record in reader:
            start = previous_line + 1
            previous_line = reader.line_num
            if not record:
                continue
            if len(record) != len(header):
                sys.stderr.write("malformed row: line %d\n" % start)
                return 4
            rows.append([normalize(cell) for cell in record])

    rows.sort(key=lambda row: (row[0], row[1] if len(row) > 1 else ""))

    target.parent.mkdir(parents=True, exist_ok=True)
    with open(target, "w", encoding="utf-8", newline="") as handle:
        handle.write("\t".join(header) + "\n")
        for row in rows:
            handle.write("\t".join(row) + "\n")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))
PYEOF

chmod +x bin/canon
./bin/canon data/orders.csv out/orders.tsv