arcpy 土地整治报备坐标文件导出(解决内环问题)

一、工具截图

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

二、导出文件

在这里插入图片描述

三、脚本

# coding=utf-8
import json
import sys
import arcpy
import os


def set_encoding():
    """
    set system encoding.
    """
    a, b, c = sys.stdin, sys.stdout, sys.stderr
    reload(sys)
    sys.setdefaultencoding("utf-8")
    sys.stdin, sys.stdout, sys.stderr = a, b, c


def ring_point_count(feature):
    """
    count point number.
    :type feature: dict
    :param feature:
    :return:
    """
    count = 0
    for ring in feature["geometry"]["rings"]:
        count += len(ring)
    return count


def reset_num(coordinate):
    """
    reset last one serial number.
    :type coordinate: list
    :param coordinate:
    """
    coordinate[-1][0] = "J1"


def load_json(path):
    """
    load json file from disk.
    :type path: str
    :param path:
    :return:
    """
    with open(path.decode("utf-8"), "r") as f:
        return json.load(f)


def feature_maps(features, configure):
    """
    get a new feature json of list.
    :param features:
    :type features: dict
    :param configure:
    :type configure: dict
    :return: feature json of list
    """
    maps = []
    feature_map = []
    point_max = int(configure["attr-desc"]["point-max-num"])
    count = 0
    index = 1
    for feature in features:
        rp_count = ring_point_count(feature)
        if (count + rp_count) > point_max:
            maps.append(feature_map)
            feature_map = []
            count = 0
            index = 1
        index_feature = {
            "index": str(index),
            "rp_count": str(rp_count),
            "attributes": feature["attributes"],
            "rings": feature["geometry"]["rings"]
        }
        feature_map.append(index_feature)
        count += rp_count
        index += 1
    maps.append(feature_map)
    return maps


def analyse_overview(feature, configure):
    """
    get a overview info.
    :type configure: dict
    :type feature: dict
    :param feature:
    :param configure:
    :return:
    """
    attributes = feature["attributes"]
    # 坐标点个数,地块面积,地块号,地块名称,图形属性,图幅号,地块用途,备注,@
    return "{coordinate_count},{area},{plot_num},{plot_name},{attribute},{sheet_designation},{land_use},{remark},@".format(
        coordinate_count=feature["rp_count"],
        area=attributes[configure["layer-meta"]["serial-num-field"]],
        plot_num=attributes[configure["layer-meta"]["area-field"]],
        plot_name=configure["attr-desc"]["prefix"] + feature["index"],
        attribute="",
        sheet_designation="",
        land_use="",
        remark=configure["attr-desc"]["layer-remark"]
    )


def analyse_coordinates(feature):
    """
    get coordinates from feature.
    :type feature: dict
    :param feature:
    :return:
    """
    rings = feature["rings"]
    coordinates = [
        [["J" + str(index + 1), str(ring_index + 1), ",".join(list(map(str, coordinate[:])))] for index, coordinate in
         enumerate(ring)] for ring_index, ring in enumerate(rings)]
    return coordinates


def create_dir(path):
    """
    :type path: str
    :param path:
    """
    if not os.path.exists(path.decode("utf-8")):
        os.makedirs(path.decode("utf-8"))
    else:
        arcpy.AddError(path.decode("utf-8") + "目录已存在")


def write_header(f, configure):
    attr_desc = configure["attr-desc"]
    f.write("[属性描述]\n")
    f.write("格式版本号=" + attr_desc["version"] + "\n")
    f.write("数据生产单位=" + attr_desc["producer"] + "\n")
    f.write("数据生产日期=" + attr_desc["date"] + "\n")
    f.write("坐标系=" + attr_desc["coordinate"] + "\n")
    f.write("几度分带=" + attr_desc["degree"] + "\n")
    f.write("投影类型=" + attr_desc["projection"] + "\n")
    f.write("计量单位=" + attr_desc["unit"] + "\n")
    f.write("带号=" + attr_desc["degree-num"] + "\n")
    f.write("精度=" + attr_desc["precision"] + "\n")
    f.write("转换参数=" + attr_desc["conversion-parameter"] + "\n")
    f.write("[地块坐标]\n")


def convert(export_info, configure):
    """
    create a new file of coordinates.
    :type export_info: dict
    :param export_info:
    """
    geojson = load_json(export_info["jsonfile"])
    features = geojson["features"]
    create_dir(export_info["export_dir"])
    for index, feature_map in enumerate(feature_maps(features, configure)):
        out_filename = "{0}\\{1}-{2}.txt".format(export_info["export_dir"], export_info["filename"], str(index))
        with open(out_filename.decode("utf-8"), "w") as f:
            write_header(f, configure)
            for feature in feature_map:
                overview = analyse_overview(feature, configure)
                f.write(overview)
                f.write("\n")
                for coordinate in analyse_coordinates(feature):
                    reset_num(coordinate)
                    for item in coordinate:
                        f.write(",".join(item) + "\n")


def analyse_path(workspace, temp_workspace, layer):
    """
    get export information.
    :type layer: str
    :type temp_workspace: str
    :type workspace: str
    :param workspace:
    :param temp_workspace:
    :param layer:
    :return:
    """
    filename = os.path.basename(layer).split(".")[0]
    export_info = {
        "layer": layer,
        "filename": filename,
        "jsonfile": "{root}\\{filename}.json".format(root=temp_workspace, filename=filename),
        "export_dir": "{root}\\{layer_dir}".format(root=workspace, layer_dir=filename)
    }
    return export_info


def check_path(workspace, temp_workspace, layers, skip_repeat):
    """
    check whether the path exists.
    :param workspace:
    :param temp_workspace:
    :param layers:
    :return:
    """
    export_infos = []
    for layer in layers:
        export_info = analyse_path(workspace, temp_workspace, layer)
        if skip_repeat == "true":
            if os.path.exists(export_info["jsonfile"].decode("utf-8")):
                continue
            elif os.path.exists(export_info["export_dir"].decode("utf-8")):
                continue
            else:
                export_infos.append(export_info)
        else:
            if os.path.exists(export_info["jsonfile"].decode("utf-8")):
                arcpy.AddError(export_info["jsonfile"] + "目录已存在")
            elif os.path.exists(export_info["export_dir"].decode("utf-8")):
                arcpy.AddError(export_info["export_dir"] + "目录已存在")
            else:
                export_infos.append(export_info)
    return export_infos


def export_json(export_infos):
    """
    export all json file
    :param export_infos:
    """
    for export_info in export_infos:
        arcpy.FeaturesToJSON_conversion(export_info["layer"], export_info["jsonfile"])


def export_all_file(export_infos, configure):
    """
    export file
    :param export_infos:
    :param configure:
    """
    for export_info in export_infos:
        convert(export_info, configure)


def export_file(workspace, temp_workspace, layers, configure, skip_repeat):
    """
    export file.
    :type configure: dict
    :type layers: list
    :type temp_workspace: str
    :type workspace: str
    :param workspace:
    :param temp_workspace:
    :param layers:
    :param configure:
    """
    arcpy.AddMessage("检查路径是否重复......")
    export_infos = check_path(workspace, temp_workspace, layers, skip_repeat)
    arcpy.AddMessage("导出JSON格式......")
    export_json(export_infos)
    arcpy.AddMessage("导出标准格式......")
    export_all_file(export_infos, configure)
    arcpy.AddMessage("导出完毕")


if __name__ == "__main__":
    set_encoding()
    workspace = arcpy.GetParameterAsText(0)
    temp_workspace = arcpy.GetParameterAsText(1)
    layers = arcpy.GetParameterAsText(2).split(";")
    skip_repeat = arcpy.GetParameterAsText(3)
    configure = {
        "layer-meta": {
            "serial-num-field": arcpy.GetParameterAsText(4),
            "area-field": arcpy.GetParameterAsText(5),
        },
        "attr-desc": {
            "version": arcpy.GetParameterAsText(6),
            "producer": arcpy.GetParameterAsText(7),
            "date": arcpy.GetParameterAsText(8),
            "coordinate": arcpy.GetParameterAsText(9),
            "degree": arcpy.GetParameterAsText(10),
            "projection": arcpy.GetParameterAsText(11),
            "unit": arcpy.GetParameterAsText(12),
            "degree-num": arcpy.GetParameterAsText(13),
            "precision": arcpy.GetParameterAsText(14),
            "conversion-parameter": arcpy.GetParameterAsText(15),
            "prefix": arcpy.GetParameterAsText(16),
            "point-max-num": arcpy.GetParameterAsText(17),
            "layer-remark": arcpy.GetParameterAsText(18)
        },
        "encode": arcpy.GetParameterAsText(19)
    }

    export_file(workspace, temp_workspace, layers, configure, skip_repeat)
  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
ArcGIS是一款功能强大的地理信息系统软件,用于地图制作、空间分析和地理数据管理。在ArcGIS中,如果我们希望将信息以txt格式进行批量导出,可以使用一些自定义的工具来实现。 首先,我们可以创建一个Python脚本来编写我们的导出工具。在脚本中,我们可以使用arcpy模块中的相关函数来实现数据的读取和导出。 首先,我们需要使用arcpy.env.workspace函数指定我们的工作空间,即包含数据的文件夹路径。接下来,使用arcpy.ListFeatureClasses函数获取所有的要素类文件。然后,使用for循逐个读取每个要素类,并将要素类中的属性信息提取出来。 我们可以使用arcpy.da.SearchCursor函数来读取要素类的属性表,并使用for循来逐个读取每条记录。在每次循中,我们可以将属性信息写入一个txt文件中。在写入文件之前,我们可以对属性信息进行格式化,以便更好地呈现数据。 在每个要素类处理完成之后,我们可以关闭文件,并继续下一个要素类的处理,直到所有要素类的属性信息都被写入了txt文件中。 最后,我们可以通过运行Python脚本,实现txt批量导出工具。只需要等待脚本运行完成,就可以在指定的输出文件夹中找到生成的txt文件。 通过这个自定义的工具,我们可以方便地将信息以txt格式进行批量导出。无论是单个要素类还是多个要素类,都可以通过这个工具快速高效地处理和导出信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值