利用Python完成某一城市的CAD路网数据
需要进一步优化
import re
import time
import requests
from xpinyin import Pinyin
def getCityRpadDataByOSM(cityName):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded"}
data = '<osm-script><query type="relation"><has-kv k="boundary" v="administrative"/><has-kv k="name:zh" v="' + cityName + '"/></query><print/></osm-script>'
url = "http://www.overpass-api.de/api/interpreter"
response = requests.post(url, data=data.encode(), headers=headers)
# 利用正则表达式提取 id
match = re.search('<relation id="(.*?)">', response.text)
id = match.group(1)
# id 需要 10位
if id:
id = str(3600000000 + int(id))
print('城市id:', id)
else:
return
data2 = '<osm-script timeout="1800" element-limit="100000000"><union><area-query ref="' + id + '"/><recurse type="node-relation" into="rels"/><recurse type="node-way"/><recurse type="way-relation"/></union><union><item/><recurse type="way-node"/></union><print mode="body"/></osm-script>'
response2 = requests.post(url, data=data2, headers=headers)
if len(response2.text) > 1000:
# 这里设置阀值是因为 网络问题会导致出现超时,丢掉这个包
p = Pinyin()
cityname = p.get_pinyin(cityName)
with open(cityname + ".osm", "w", encoding='utf-8') as f:
f.write(response2.text)
# print('第一步:爬取指定城市路网')
# print('输入城市名称,请写全称:')
# city = str(input())
city = '青岛市'
p = Pinyin()
cityname = str(p.get_pinyin(city))
# getCityRpadDataByOSM(cityName=city)
print('已获取到osm文件')
print('等待5s...')
time.sleep(5)
print('第二步:路网数据解析')
import osm2gmns as og
net = og.getNetFromOSMFile(cityname + '.osm')
og.outputNetToCSV(net, output_folder='output')
print('线形节点文件在output文件夹')
# print('道路等级和编号如下:'
# '1:高速公路'
# '2:国道/一级公路'
# '3:省道'
# '4:县道'
# '5:乡道')
# print('请输入所需要的路网等级,如果需要全部,请输入0')
# num = int(input())
import pandas as pd
data = pd.read_csv('output/link.csv', encoding='GBK')
df = pd.DataFrame(data)
df1 = df['name']
df2 = df['link_type_name']
df3 = df['geometry'].str.replace('LINESTRING ', '')
df0 = [df1, df2, df3]
con = pd.concat(df0, axis=1)
con.to_csv('temp.csv', index=False)
data2 = pd.read_csv(r'temp.csv')
highway = data2[data2['link_type_name'] == 'motorway'] # 高速
wayG = data2[data2['link_type_name'] == 'trunk'] # 国道
wayS = data2[data2['link_type_name'] == 'primary'] # 省道
wayX = data2[data2['link_type_name'] == 'secondary'] # 县道
wayY = data2[data2['link_type_name'] == 'tertiary'] # 乡道
# coding:utf-8
def arr(inroad, outroad):
with open('temp.txt', 'w') as f:
f.truncate(0)
f.close()
with open('temp2.txt', 'w') as f:
f.truncate(0)
f.close()
file1 = open(inroad, 'r', encoding='utf-8') # 打开要去掉空行的文件
file2 = open('temp.txt', 'w', encoding='utf-8') # 生成没有空行的文件
for line in file1.readlines():
if line == '\n':
line = line.strip('\n')
file2.write(line)
file1.close()
file2.close()
for line in open("temp.txt"):
l2 = line.replace(", ", ";")
l3 = l2.replace(" ", ",")
l4 = l3.replace(";", ",0,")
l5 = l4.replace('"(', "")
l6 = l5.replace(')"', ",0")
print(l6)
with open('temp2.txt', 'a+') as gd:
print(l6, file=gd)
gd.close()
file1 = open('temp2.txt', 'r', encoding='utf-8') # 打开要去掉空行的文件
file2 = open(outroad, 'w', encoding='utf-8') # 生成没有空行的文件
for line in file1.readlines():
if line == '\n':
line = line.strip('\n')
file2.write(line)
file1.close()
file2.close()
import os
os.remove('temp2.txt')
os.remove('temp.txt')
def writelevel(level, lname):
level['geometry'].to_csv('output/' + lname + '.txt', index=False, index_label=False, header=False)
arr('output/' + lname + '.txt', 'output/' + lname + '_final.txt')
writelevel(highway, 'highway')
writelevel(wayG, 'G_road')
writelevel(wayS, 'S_road')
writelevel(wayX, 'X_road')
writelevel(wayY, 'Y_road')
#
# if num == 1:
# writelevel(highway, 'highway')
# elif num == 2:
# writelevel(wayG, 'G_road')
# elif num == 3:
# writelevel(wayS, 'S_road')
# elif num == 4:
# writelevel(wayX, 'X_road')
# elif num == 5:
# writelevel(wayY, 'Y_road')
# else:
# print('编号输入错误,默认全部生成')
# writelevel(highway, 'highway')
# writelevel(wayG, 'G_road')
# writelevel(wayS, 'S_road')
# writelevel(wayX, 'X_road')
# writelevel(wayY, 'Y_road')
import os
os.remove('temp.csv')
print('绘制CAD图,在开始之前,请打开CAD,然后按任意键继续')
print(input())
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
=============================
Author: DalNur
Email: [email protected]
=============================
"""
import time
import pythoncom
import win32com.client
wincad = win32com.client.Dispatch("AutoCAD.Application")
doc = wincad.ActiveDocument
doc.Utility.Prompt("Hello! Autocad from pywin32com.\n")
msp = doc.ModelSpace
print(doc.Name)
def vtpnt(x, y, z=0):
return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, (x, y, z))
def vtobj(obj):
return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_DISPATCH, obj)
def vtfloat(lst):
return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, lst)
#
def g(pnts, r, g, b):
points = vtfloat(pnts)
plineObj = msp.AddPolyline(points)
version = wincad.Application.Version[:2] # 当前CAD的版本号
clr = wincad.Application.GetInterfaceObject("AutoCAD.AcCmColor.%s" % version)
clr.SetRGB(r, g, b) # 创建红色
doc.preferences.LineweightDisplay = 1
plineObj.TrueColor = clr
doc.Application.Update()
def impf(filename, R, G, B):
with open(filename, 'r') as f:
my_data = f.readlines()
for line in my_data:
line_data = line.split()
s = [float(i) for i in line_data[0].split(',')]
print(s)
g(s, R, G, B)
time.sleep(0.1)
impf('output/highway_final.txt', 255, 0, 0)
impf('output/G_road_final.txt', 0, 255, 0)
impf('output/S_road_final.txt', 0, 0, 255)
impf('output/X_road_final.txt', 0, 255, 255)
impf('output/Y_road_final.txt', 255, 0, 255)
标签:map,openstreet,Python,writelevel,print,line,txt,road,data2
From: https://www.cnblogs.com/agonygone/p/16870872.html