Converting Cube Transit Line Files to Shapefile with Python

I’m fairly certain this is not the first time I’ve written a script like this, but it’s the first time in a long time. This script should work out of the box for most Cube transit line files, even with differences in attributes used.

This script is a function that takes the transit line file, the line indicator (which is always going to be “LINE” when using PT format transit). There is a parameter for a key id that I think I coded out (it would have been an index in the dataframe), and a table of coordinates that should be indexed with the node number.

import pandas as pd
import numpy as np
import re
import geopandas as gpd
from shapely.geometry import Point, LineString
def read_card(input_file, group_id, key_id, nxy_table):
with open(input_file, 'r') as fr:
lines = fr.readlines()
lines = [line.rstrip('\n') for line in lines]
lines = [line for line in lines if line[0] != ';']
lines = ''.join(lines)
lines = lines.split(group_id)
lines = [dict(re.findall(r'(\S+)\s*\=\s*(.*?)\s*(?=\S+\s*\=|$)', line)) for line in lines]
out_lines = []
for line in lines:
if 'NAME' in line.keys():
x = {}
x['route_id'] = line['NAME']
for k, v in line.items():
if not k in ['NAME', 'N']:
x[k] = v.replace('"',"").replace(',','')
coords = nxy_table.loc[[abs(int(n)) for n in line['N'].replace('\n','').replace(' ', '').split(',')]]
geom = LineString([tuple(x) for x in coords.to_numpy()])
x['geometry'] = geom
out_lines.append(x)
return gpd.GeoDataFrame(out_lines)
transit_lines = read_card(r'path\to\transit.lin', 'LINE', 'NAME', nodes[['N', 'X', 'Y']].set_index('N'))
transit_lines.to_file('trn_routes.shp')

Comments from Other Sites

Comments are closed.