upstream/convert_characters/convert_characters.py
1#!/usr/bin/env python
2"""
3By, Guruprasad Ananda.
4"""
5from __future__ import print_function
6
7import re
8import sys
9
10
11def main():
12 if len(sys.argv) != 4:
13 sys.exit("usage: convert_characters infile from_char outfile")
14
15 try:
16 fin = open(sys.argv[1], 'r')
17 except Exception:
18 sys.exit("Input file cannot be opened for reading.")
19
20 from_char = sys.argv[2]
21
22 try:
23 fout = open(sys.argv[3], 'w')
24 except Exception:
25 sys.exit("Output file cannot be opened for writing.")
26
27 char_dict = {'T': r'\t', 's': r'\s', 'Dt': r'\.', 'C': r',', 'D': r'-',
28 'U': r'_', 'P': r'\|', 'Co': r':'}
29 # making an RE to match 1 or more occurences.
30 from_ch = char_dict[from_char] + '+'
31 skipped = 0
32
33 for line in fin:
34 line = line.strip()
35 try:
36 fout.write("%s\n" % (re.sub(from_ch, '\t', line)))
37 except Exception:
38 skipped += 1
39
40 if skipped:
41 print("Skipped %d lines as invalid." % skipped)
42
43
44if __name__ == "__main__":
45 main()