Project

General

Profile

1 4591 aaronmk
#!/usr/bin/env python
2
# Translates a spreadsheet column using a dictionary.
3
# Unrecognized names are left untouched, permitting successive runs on different
4
# dictionaries.
5
# Case- and punctuation-sensitive. (Use canon first for case-insensitivity.)
6
7
import csv
8
import sys
9
10
def main():
11
    try: _prog_name, col_num, dict_path = sys.argv
12
    except ValueError: raise SystemExit('Usage: '+sys.argv[0]
13
        +' <in col# dict [| '+sys.argv[0]+' col# dict_2]... >out')
14
    col_num = int(col_num)
15
16
    # Get dict
17
    dict_ = {}
18
    stream = open(dict_path, 'rb')
19
    reader = csv.reader(stream)
20
    reader.next() # skip header
21
    for from_, to in reader: dict_[from_] = to
22
    stream.close()
23
24
    # Translate input
25
    reader = csv.reader(sys.stdin)
26
    writer = csv.writer(sys.stdout)
27
    writer.writerow(reader.next()) # pass through header
28
    for row in reader:
29
        term = row[col_num]
30
        try: row[col_num] = dict_[term]
31
        except KeyError: pass
32
        writer.writerow(row)
33
34
main()