1
1
#!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
2
3
3
4
import csv
4
5
import sys
5
- import getopt
6
+ import argparse
6
7
from coordTransform_utils import gcj02_to_bd09
7
8
from coordTransform_utils import bd09_to_gcj02
8
9
from coordTransform_utils import wgs84_to_gcj02
9
10
from coordTransform_utils import gcj02_to_wgs84
10
11
from coordTransform_utils import bd09_to_wgs84
11
12
from coordTransform_utils import wgs84_to_bd09
12
13
13
- # Configuation
14
+ # Configuration
14
15
# Input file name
15
16
INPUT = ''
16
17
# Output file name
17
18
OUTPUT = ''
18
19
# Convert type: g2b, b2g, w2g, g2w, b2w, w2b
19
20
TYPE = ''
21
+ # lng column name
22
+ LNG_COLUMN = ''
23
+ # lat column name
24
+ LAT_COLUMN = ''
25
+ # Skip invalid row
26
+ SKIP_INVALID_ROW = False
20
27
21
28
def convert ():
22
29
with open (INPUT , 'r' ) as input_file :
23
30
input_file_reader = csv .reader (input_file )
31
+ headers = next (input_file_reader )
32
+ lng_index , lat_index = get_lng_lat_index (headers )
24
33
results = []
25
- for lat , lng in input_file_reader :
26
- result = convert_by_type (float (lng ), float (lat ), TYPE )
34
+
35
+ for index , row in enumerate (input_file_reader ):
36
+ result = []
37
+ try :
38
+ result = convert_by_type (float (row [lng_index ]), float (row [lat_index ]), TYPE )
39
+ except ValueError :
40
+ # Deal with ValueError(invalid lng or lat)
41
+ # print(index + 2, row[lng_index], row[lat_index]) # '+ 2' is due to zero-based index and first row is header
42
+ result = row [lng_index ], row [lat_index ]
27
43
results .append (result )
28
44
29
45
with open (OUTPUT , 'w' ) as output_file :
30
46
output_file_writer = csv .writer (output_file )
31
- for result in results :
32
- output_file_writer .writerow (result )
47
+
48
+ with open (INPUT , 'r' ) as input_file :
49
+ input_file_reader = csv .reader (input_file )
50
+ headers = next (input_file_reader )
51
+ lng_index , lat_index = get_lng_lat_index (headers )
52
+
53
+ output_file_writer .writerow (headers )
54
+ for index , row in enumerate (input_file_reader ):
55
+ row [lng_index ] = results [index ][0 ]
56
+ row [lat_index ] = results [index ][1 ]
57
+ if type (row [lng_index ]) is not float or type (row [lat_index ]) is not float :
58
+ # Data is invalid
59
+ if SKIP_INVALID_ROW :
60
+ # Skip invalid row
61
+ pass
62
+ else :
63
+ # Reserve invalid row
64
+ output_file_writer .writerow (row )
65
+ else :
66
+ # Data is valid
67
+ output_file_writer .writerow (row )
68
+
69
+ def get_lng_lat_index (headers ):
70
+ try :
71
+ if LNG_COLUMN == '' and LAT_COLUMN == '' :
72
+ return [headers .index ('lng' ), headers .index ('lat' )]
73
+ else :
74
+ return [headers .index (LNG_COLUMN ), headers .index (LAT_COLUMN )]
75
+ except ValueError as error :
76
+ print ('Error: ' + str (error ).split ('is' , 1 )[0 ] + 'is missing from csv header. Or use -n or -a to specify custom column name for lng or lat.' )
77
+ sys .exit ()
33
78
34
79
def convert_by_type (lng , lat , type ):
35
80
if type == 'g2b' :
@@ -45,37 +90,38 @@ def convert_by_type(lng, lat, type):
45
90
elif type == 'w2b' :
46
91
return wgs84_to_bd09 (lng , lat )
47
92
else :
48
- print ('Usage: The < type> must be in one of g2b, b2g, w2g, g2w, b2w, w2b' )
93
+ print ('Usage: type must be in one of g2b, b2g, w2g, g2w, b2w, w2b' )
49
94
sys .exit ()
50
95
51
- def usage ():
52
- print ('Usage: coord_converter.py -i <input> -o <output> -t <type>' )
53
- print ('' )
54
- print ('where <type> is one of:' )
55
- print (' g2b, b2g, w2g, g2w, b2w, w2b' )
56
- print ('' )
57
- print ('Example: coord_converter.py -i /path/to/input_file.csv -o /path/to/output_file.csv -t b2g' )
96
+ if __name__ == '__main__' :
97
+ parser = argparse .ArgumentParser (description = 'Convert coordinates in csv files.' , usage = '%(prog)s [-h] -i INPUT -o OUTPUT -t TYPE [-n LNG_COLUMN] [-a LAT_COLUMN] [-s SKIP_INVALID_ROW]' , formatter_class = argparse .ArgumentDefaultsHelpFormatter )
58
98
59
- if __name__ == "__main__" :
60
- argv = sys .argv [1 :]
61
- try :
62
- opts , args = getopt .getopt (argv , "hi:o:t:" , ["input=" , "output=" , "type=" ])
63
- except getopt .GetoptError :
64
- usage ()
65
- sys .exit (2 )
66
- for opt , arg in opts :
67
- if opt == '-h' :
68
- usage ()
69
- sys .exit ()
70
- elif opt in ("-i" , "--input" ):
71
- INPUT = arg
72
- elif opt in ("-o" , "--output" ):
73
- OUTPUT = arg
74
- elif opt in ("-t" , "--type" ):
75
- TYPE = arg
76
-
77
- if not (INPUT and OUTPUT and TYPE ):
78
- usage ()
79
- sys .exit ()
99
+ group = parser .add_argument_group ('arguments' )
100
+
101
+ group .add_argument ('-i' , '--input' , help = 'Location of input file' , default = argparse .SUPPRESS , metavar = '' )
102
+ group .add_argument ('-o' , '--output' , help = 'Location of output file' , default = argparse .SUPPRESS , metavar = '' )
103
+ group .add_argument ('-t' , '--type' , help = 'Convert type, must be one of: g2b, b2g, w2g, g2w, b2w, w2b' , default = argparse .SUPPRESS , metavar = '' )
104
+ group .add_argument ('-n' , '--lng_column' , help = 'Column name for longitude' , default = 'lng' , metavar = '' )
105
+ group .add_argument ('-a' , '--lat_column' , help = 'Column name for latitude' , default = 'lat' , metavar = '' )
106
+ group .add_argument ('-s' , '--skip_invalid_row' , help = 'Whether to skip invalid row' , default = False , type = bool , metavar = '' )
107
+
108
+ args = parser .parse_args ()
109
+ # print('\nArguments you provide are:')
110
+ # for arg in vars(args):
111
+ # print '{0:20} {1}'.format(arg, str(getattr(args, arg)))
112
+
113
+ # Get arguments
114
+ if not args .input or not args .output or not args .type :
115
+ parser .print_help ()
116
+ else :
117
+ INPUT = args .input
118
+ OUTPUT = args .output
119
+ TYPE = args .type
120
+
121
+ if args .lng_column and args .lat_column :
122
+ LNG_COLUMN , LAT_COLUMN = args .lng_column , args .lat_column
123
+
124
+ if args .skip_invalid_row :
125
+ SKIP_INVALID_ROW = args .skip_invalid_row
80
126
81
127
convert ()
0 commit comments