【ArcGIS之AI写Python代码】:(1)新建shapefile图层

        你能想到吗?原来AI还可以这么玩。在零Python编程基础的情况,是否能在ChatGPT等AI的加持下,写出适合Arcgis软件运行的脚本代码?

        因为这个突发奇想,本人开启了零Python编程基础用AI编写适合ArcGIS运行的脚本代码的挑战之路,本期先从简单入门,新建shapefile图层。

一、基本要求

         用AI编写一段Python代码,通过运行,实现新建一个空的shapefile图层。

二、实现过程

          AI给我们的基本流程如下:

          1、首先。设置工作空间。

# 设置工作空间  
arcpy.env.workspace = r"C:\data\my_shapefile"

          2、定义shapefile名称和字段列表

# 定义shapefile名称和字段列表  
shapefile_name = "my_shapefile.shp"  
field_names = ["SHAPE@", "ID", "NAME"]  

        3、创建shapefile图层 

# 创建shapefile图层  
arcpy.CreateFeatureclass_management(arcpy.env.workspace, shapefile_name, "POLYGON", "", "", "")

        4、添加字段

# 添加字段  
for field_name in field_names:  
    arcpy.AddField_management(shapefile_name, field_name, field_type="TEXT") 

5、 删除新创建的空记录  

# 删除新创建的空记录  
arcpy.DeleteFeatures_management(shapefile_name)  

6、打印输出结果信息

三、代码解读

        完整代码如下:

import arcpy  
  
# 设置工作空间  
arcpy.env.workspace = r"C:\data\my_shapefile"  
  
# 定义shapefile名称和字段列表  
shapefile_name = "my_shapefile.shp"  
field_names = ["SHAPE@", "ID", "NAME"]  
  
# 创建shapefile图层  
arcpy.CreateFeatureclass_management(arcpy.env.workspace, shapefile_name, "POLYGON", "", "", "")  
  
# 添加字段  
for field_name in field_names:  
    arcpy.AddField_management(shapefile_name, field_name, field_type="TEXT")  
  
# 删除新创建的空记录  
arcpy.DeleteFeatures_management(shapefile_name)  
  
# 运行完成提示  
print(" Shapefile layer created successfully!")

        这段代码基本意思是:设置一个工作空间,在工作空间中创建一个名为"my_shapefile.shp"的shapefile图层,并用CreateFeatureclass_management添加三个字段:SHAPE@(用于存储几何信息)、ID(用于存储标识符)和NAME(用于存储名称)。最后,它会删除新创建的空记录,并在运行完成后打印出成功创建的提示信息。

四、代码改进

        以上代码成功创建了shapefile图层,但是还是提示了错误信息。

提示ID已经存在!

ERROR 000012: ID already exists
Failed to execute (AddField).

这个时候,我们只需换个ID名就好了,比如换成NID,NEWID等就好了。

以上就是AI编写适合ArcGIS运行的脚本代码,不足之处请多多指点,多提宝贵意见。

你可能感兴趣的:(ARCGIS,python)