import os
from qgis.core import (
QgsVectorLayer,
QgsVectorFileWriter
)
# 解析 S57 图层信息的函数
def extract_s57_layer_info(s57layers: list[str]) -> list[tuple]:
extracted_info = []
# 内部的解析函数
def parse_layer_info(layer_info):
# 以 "!!::!!" 分割字符串
parts = layer_info.split('!!::!!')
# 提取序号、图层名称、几何类型
layer_id = parts[0] # 序号
layer_name = parts[1] # 图层名称
geometry_type = parts[3] # 几何类型
return layer_id, layer_name, geometry_type
# 遍历所有图层,解析并存储信息
for layer in s57layers:
layer_id, layer_name, geometry_type = parse_layer_info(layer)
extracted_info.append((layer_id, layer_name, geometry_type))
return extracted_info
def main():
# 确保输出文件夹存在
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 加载 S57 文件为 OGR 数据源
data_source_uri = f"{s57_file}"
# 加载 S57 文件的所有图层到项目
layer = QgsVectorLayer(data_source_uri, "S57 Layer", "ogr")
if not layer.isValid():
print(f"S57 文件 '{s57_file}' 无法加载为图层")
else:
# 加载 S57 文件的所有子图层到图层组中
sublayers = layer.dataProvider().subLayers()
sublayers_info = extract_s57_layer_info(sublayers)
for sublayer_info in sublayers_info:
sublayer_id, sublayer_name, geometry_type = sublayer_info
# 构建子图层的 URI
sublayer_uri = f"{s57_file}|layername={sublayer_name}"
# 加载子图层
sublayer = QgsVectorLayer(sublayer_uri, sublayer_name, "ogr")
if geometry_type == "None":
continue
if sublayer.isValid():
# 构建输出文件路径
output_file = os.path.join(output_folder, f"{sublayer_name}_{geometry_type}.shp")
# 导出图层为 Shapefile 格式
error = QgsVectorFileWriter.writeAsVectorFormat(
layer, output_file, "UTF-8", layer.crs(), "ESRI Shapefile"
)
if error == QgsVectorFileWriter.NoError:
print(f"图层 '{sublayer_name}' ({geometry_type}) 成功导出为 '{output_file}'")
else:
print(f"图层 '{sublayer_name}' 导出失败: {error}")
else:
print(f"子图层 '{sublayer_name}' 转换失败")
print(f"S57 文件 '{s57_file}' 的所有子图层已转换完成 '{output_folder}'")
if __name__ == '__main__':
# S57 文件路径
s57_file = r"G:\GIS-DATA\s57\C1515435.000"
# 输出文件夹路径
output_folder = r"G:\GIS-DATA\s57\test"
main()
标签:info,core,layer,name,qgis,sublayer,s57,图层
From: https://www.cnblogs.com/echohye/p/18497849