在Python中,尝试将地理编码的tsv文件转换为geojson格式

时间:2015-05-22 09:35:51

标签: python json geocoding geojson tsv

尝试将地理编码的TSV文件转换为JSON格式,但我遇到了问题。这是代码:

import geojson
import csv

def create_map(datafile):
    geo_map = {"type":"FeatureCollection"}
    item_list = []
    datablock = list(csv.reader(datafile))
    for i, line in enumerate(datablock):
        data = {}
        data['type'] = 'Feature'
        data['id'] = i
        data['properties']={'title': line['Movie Title'],
                           'description': line['Amenities'],
                           'date': line['Date']}
        data['name'] = {line['Location']}
        data['geometry'] = {'type':'Point',
                           'coordinates':(line['Lat'], line['Lng'])}
        item_list.append(data)
    for point in item_list:
        geo_map.setdefault('features', []).append(point)
    with open("thedamngeojson.geojson", 'w') as f:
        f.write(geojson.dumps(geo_map))

create_map('MovieParksGeocode2.tsv')

我在TypeError:list indices must be integers, not str行找到了data['properties'],但我不明白,我不知道如何为geoJSON字段设置值?

我读的文件在这些键下有值:位置电影标题日期设施Lat Lng

此处可查看该文件:https://github.com/yongcho822/Movies-in-the-park/blob/master/MovieParksGeocodeTest.tsv

谢谢你们,一如既往地非常感谢。

1 个答案:

答案 0 :(得分:1)

你有几件事需要修复。

1.您的TSV包含带双引号的换行符。我不认为这是有意的,会引起一些问题。

Location    Movie Title Date    Amenities   Formatted_Address   Lat Lng
"
Edgebrook Park, Chicago "   A League of Their Own   7-Jun   "
Family friendly activities and games. Also: crying is allowed." Edgebrook Park, 6525 North Hiawatha Avenue, Chicago, IL 60646, USA  41.9998876  -87.7627672
"

2.您不需要geojson模块来转储JSON - 这是GeoJSON的全部内容。只需改为import json

3.您正在尝试阅读TSV,但您没有包含此所需的delimiter=\t选项。

4.您正在尝试读取行中的键,但您没有使用DictReader为您执行此操作。请参阅上面提到的关于索引的TypeError

查看下面的修改后的代码块。您仍然需要将TSV修复为有效的TSV。

import csv
import json

def create_map(datafile):
    geo_map = {"type":"FeatureCollection"}
    item_list = []
    with open(datafile,'r') as tsvfile:
        reader = csv.DictReader(tsvfile,delimiter='\t')
        for i, line in enumerate(reader):
            print line
            data = {}
            data['type'] = 'Feature'
            data['id'] = i
            data['properties']={'title': line['Movie Title'],
                               'description': line['Amenities'],
                               'date': line['Date']}
            data['name'] = {line['Location']}
            data['geometry'] = {'type':'Point',
                               'coordinates':(line['Lat'], line['Lng'])}
            item_list.append(data)
        for point in item_list:
            geo_map.setdefault('features', []).append(point)
        with open("thedamngeojson.geojson", 'w') as f:
            f.write(json.dumps(geo_map))

create_map('MovieParksGeocode2.tsv')