Skip to content

Commit a7febd8

Browse files
authored
Merge pull request #21 from zuzhi/master
支持指定经纬度字段
2 parents f791cd5 + f7fe294 commit a7febd8

File tree

3 files changed

+116
-43
lines changed

3 files changed

+116
-43
lines changed

README.md

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
需要js版本可以移步[coordtransform](https://github.com/wandergis/coordtransform)
88

9-
## 使用说明
9+
## 使用说明(coordTransform_utils.py)
1010

1111
### 方法说明
1212

@@ -27,22 +27,46 @@ g.geocode('北京市朝阳区朝阳公园')
2727
### 测试
2828

2929
```bash
30-
# 测试
30+
# 测试(转换坐标 128.543,37.065 )
3131
$ python coordTransform_utils.py
3232
[128.54944656269413, 37.07113427883019] [128.5365893261212, 37.058754503281534] [128.54820547949757, 37.065651049489816] [128.53779452050244, 37.06434895051018] [128.53136876750008, 37.0580926428705] [128.55468192918485, 37.07168344938498] None
3333
```
3434

35-
## 批量转换csv文件(coord_converter.py)
35+
## 批量转换csv文件使用说明(coord_converter.py)
3636

37-
使用方法
37+
### 使用说明
3838

3939
```bash
40+
# 查看使用帮助
4041
$ python coord_converter.py -h
4142

42-
Usage: coord_converter.py -i <input> -o <output> -t <type>
43+
usage: coord_converter.py [-h] -i INPUT -o OUTPUT -t TYPE [-n LNG_COLUMN] [-a LAT_COLUMN] [-s SKIP_INVALID_ROW]
4344

44-
where <type> is one of:
45-
g2b, b2g, w2g, g2w, b2w, w2b
45+
Convert coordinates in csv files.
4646

47-
Example: coord_converter.py -i /path/to/input_file.csv -o /path/to/output_file.csv -t b2g
47+
optional arguments:
48+
-h, --help show this help message and exit
49+
50+
arguments:
51+
-i , --input Location of input file
52+
-o , --output Location of output file
53+
-t , --type Convert type, must be one of: g2b, b2g, w2g, g2w, b2w,
54+
w2b
55+
-n , --lng_column Column name for longitude (default: lng)
56+
-a , --lat_column Column name for latitude (default: lat)
57+
-s , --skip_invalid_row
58+
Whether to skip invalid row (default: False)
59+
```
60+
61+
### 示例
62+
63+
```bash
64+
# 不指定经纬度列名(默认为'lng', 'lat')
65+
$ python coord_converter.py -i test_input.csv -o test_output.csv -t b2g
66+
67+
# 指定经纬度列名
68+
$ python coord_converter.py -i test_input.csv -o test_output.csv -t b2g -n 经度 -a 纬度
69+
70+
# 跳过无效经纬度的行(默认不跳过)
71+
$ python coord_converter.py -i test_input.csv -o test_output.csv -t b2g -n 经度 -a 纬度 -s True
4872
```

coord_converter.py

Lines changed: 81 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,80 @@
11
#!/usr/bin/python
2+
# -*- coding: utf-8 -*-
23

34
import csv
45
import sys
5-
import getopt
6+
import argparse
67
from coordTransform_utils import gcj02_to_bd09
78
from coordTransform_utils import bd09_to_gcj02
89
from coordTransform_utils import wgs84_to_gcj02
910
from coordTransform_utils import gcj02_to_wgs84
1011
from coordTransform_utils import bd09_to_wgs84
1112
from coordTransform_utils import wgs84_to_bd09
1213

13-
# Configuation
14+
# Configuration
1415
# Input file name
1516
INPUT = ''
1617
# Output file name
1718
OUTPUT = ''
1819
# Convert type: g2b, b2g, w2g, g2w, b2w, w2b
1920
TYPE = ''
21+
# lng column name
22+
LNG_COLUMN = ''
23+
# lat column name
24+
LAT_COLUMN = ''
25+
# Skip invalid row
26+
SKIP_INVALID_ROW = False
2027

2128
def convert():
2229
with open(INPUT, 'r') as input_file:
2330
input_file_reader = csv.reader(input_file)
31+
headers = next(input_file_reader)
32+
lng_index, lat_index = get_lng_lat_index(headers)
2433
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]
2743
results.append(result)
2844

2945
with open(OUTPUT, 'w') as output_file:
3046
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()
3378

3479
def convert_by_type(lng, lat, type):
3580
if type == 'g2b':
@@ -45,37 +90,38 @@ def convert_by_type(lng, lat, type):
4590
elif type == 'w2b':
4691
return wgs84_to_bd09(lng, lat)
4792
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')
4994
sys.exit()
5095

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)
5898

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
80126

81127
convert()

test_input.csv

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
lng,lat,column1
2+
116.4172,39.93889,value1
3+
102.72569,25.0444,value2

0 commit comments

Comments
 (0)