使用ArcPy批量更改要素类和字段别名吗?


14

我有一百多个FC,每个FC具有10或20个属性,每年添加或更改其别名两次或多次。不用说,这不是我要抱怨的事情。我如何使这个过程自动化?

首选Python解决方案,但会使用任何可行的方法。

我可以访问Arcgis 9.3.1和10(ArcInfo许可级别)。


1
我找到了ArcCatalog的[Edit Feature Class Schema] [1] v9.3开发人员示例。它将所选要素类的别名更改为脚本中硬编码的值。因此,这不是一个批处理过程,而是朝着这个方向前进。[1]:resources.esri.com/help/9.3/ArcGISDesktop/com/samples/...
亚光尔基

相关(基础构建模块):gis.stackexchange.com/questions/80/...
马特·威尔基

Answers:


7

从10.1版开始,AlterAliasName() 可用于重新别名表:

table = r"C:\path\to\connection.sde\OWNER.TABLE"
arcpy.AlterAliasName(table, "table_alias")

从10.3版开始,Alter Field可用于重新别名字段:

table = r"C:\path\to\connection.sde\OWNER.TABLE"
arcpy.AlterField_management(table, "FIELD_NAME", new_field_alias="field_alias")

8

在Mark Cederholm的帮助下,我有了使用python和arcobjects的有效解决方案。它的边缘很粗糙,但是完成了工作。在遵循该页面上的配方之后,创建一个新脚本,该脚本使用中的GetLibPath, NewObj, CType, OpenFeatureClass功能snippets.py。还以.csv格式创建重命名查找表:

字段到字段别名查找(att_code-name_lookup.csv):

Attrib_Name,Alias_Name
CODE,Specification Code
VALDATE,Validity Date
...

FC Alias查找的要素类(fc_code-name_lookup.csv):

"FC_Name","AliasName"
"BS_1250009_0","Navigational Aid"
"BS_1370009_2","Residential Area"
...

和脚本:

import sys
sys.path.append('k:/code')
from snippets import GetLibPath, NewObj, CType, OpenFeatureClass
sWorkingDir = "k:/code/"
sFileGDB = sWorkingDir + "blank_canvec.gdb"
sResourceDir = "k:/code/"
sFCAliasFile = sResourceDir + "fc_code-name_lookup.csv"
sAttAliasFile = sResourceDir + "att_code-name_lookup.csv"
sProduct = "ArcEditor"

def BuildFieldAliasLookup():
    lookup = {}
    f = open(sAttAliasFile, "r")
    bFirst = True
    for line in f:
        # Skip first line
        if bFirst:
            bFirst = False
            continue
        sTokens = line.replace('"','').split(',')
        sFieldName = sTokens[0]
        sAlias = sTokens[1]
        lookup[sFieldName] = sAlias
    return lookup

def AlterAlias():
    # Initialize
    from comtypes.client import GetModule
    import arcgisscripting
    sLibPath = GetLibPath()
    GetModule(sLibPath + "esriGeoDatabase.olb")
    GetModule(sLibPath + "esriDataSourcesGDB.olb")
    import comtypes.gen.esriGeoDatabase as esriGeoDatabase
    gp = arcgisscripting.create(9.3)

    try:
        gp.setproduct(sProduct)
    except:
        gp.AddMessage(gp.GetMessages(2))

    # Build field alias lookup table
    AttrLookup = BuildFieldAliasLookup()
    # Open alias file and loop through lines
    f = open(sFCAliasFile, "r")
    bFirst = True
    for line in f:
        # Skip first line
        if bFirst:
            bFirst = False
            continue
        sTokens = line.replace('"','').split(',')
        sFCName = sTokens[0]
        sAlias = sTokens[1]
        print "Processing: ", sFCName
        # Open feature class
        try:
            pFC = OpenFeatureClass(sFCName)
        except:
            print "Could not open ", sFCName
            continue
        # Alter feature class alias
        try:
            pSE = CType(pFC, esriGeoDatabase.IClassSchemaEdit)
            pSE.AlterAliasName(sAlias)
        except:
            print "Error altering class alias"
            continue
        # Alter field aliases
        try:
            for sKey in AttrLookup.keys():
                i = pFC.FindField(sKey)
                if i == -1:
                    continue
                sAlias = AttrLookup[sKey]
                pSE.AlterFieldAliasName(sKey, sAlias)
        except:
            print "Error altering field aliases"
    print "Done."

print 'Field <--> Alias lookup table is:', BuildFieldAliasLookup()
print AlterAlias()

这是如此接近我所需要的(更新字段别名)。片段的OpenFeatureClass部分是什么样的?马克的代码没有那个。谢谢

嗨,Jasperoid:您可以通过单击“添加评论”链接对特定答案发表评论,我已经将您对这个答案的回复迁移了。
scw

@Jasperiod,我将Mark的大部分代码片段移到了一个名为parco的模块中,OpenFeatureClass也是该模块。我不记得自己创建过它,但是也许我做到了。无论如何,它在第125行
马特·威尔基

6

此代码在9.3.1中对我有用...

public static void TestAlterAlias(IApplication app)
{
    // make a dictionary of old/new names
    Dictionary<string, string> nameDict = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);
    nameDict.Add("qsectionalias", "qsectionalias2");
    nameDict.Add("sursysalias", "sursysalias2");
    string[] directories =  System.IO.Directory.GetDirectories(@"D:\Projects\EmpireOil\data",@"*.gdb",
        System.IO.SearchOption.TopDirectoryOnly);
    foreach(string dir in directories)
    {
        List<IName> fcnames = GetFCNames(dir);
        foreach (IName fcName in fcnames)
        {
            ChangeFieldAliases(fcName, nameDict);
        }
    }
}

public static void ChangeFieldAliases(IName fcName, Dictionary<string, string> aliasDict)
{
    IFeatureClass fc = (IFeatureClass)fcName.Open();
    IClassSchemaEdit3 cse = (IClassSchemaEdit3)fc;
    ((ISchemaLock)fc).ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
    SortedList<string, string> changeList = new SortedList<string, string>();
    for (int i = 0; i < fc.Fields.FieldCount; i++)
    {
        string fldName = fc.Fields.get_Field(i).Name;
        string alias = fc.Fields.get_Field(i).AliasName;
        if (aliasDict.ContainsKey(alias))
        {
            changeList.Add(fldName, aliasDict[alias]);
            // set it blank for now, to avoid problems if two fields have same aliasname.
            cse.AlterFieldAliasName(fldName, "");
        }
    }

    // change the alias
    foreach (KeyValuePair<string, string> kvp in changeList)
        cse.AlterFieldAliasName(kvp.Key, kvp.Value);
    ((ISchemaLock)fc).ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
}

public static List<IName> GetFCNames(string wsPath)
{
    List<IName> names = new List<IName>();
    IWorkspaceFactory wsf = new ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactoryClass();
    IWorkspace ws = wsf.OpenFromFile(wsPath, 0);
    IEnumDatasetName enumName = ws.get_DatasetNames(esriDatasetType.esriDTAny);
    enumName.Reset();
    IDatasetName dsName = null;
    while ((dsName = enumName.Next()) != null)
    {
        if(dsName is IFeatureClassName)
            names.Add((IName)dsName);
        else if(dsName is IFeatureDatasetName)
        {
            IEnumDatasetName enumName2 = dsName.SubsetNames;
            enumName2.Reset();
            IDatasetName dsName2;
            while((dsName2=enumName2.Next())!= null)
            {
                if(dsName2 is IFeatureClassName)
                    names.Add((IName)dsName2);
            }
        }
    }
    return names;
}

谢谢Kirk,您不知道我已经尝试了多长时间了。我猜这是C#吗?
马特·威尔基

1
是的,C#。虽然没有使用featuredatasets进行测试,但是应该可以使用。
Kirk Kuykendall,2010年

3

另一个解决方案由Rob Clark提供

您可以将featureclass_to_featureclass与字段映射一起使用。是的,它创建了另一个要素类,但是您可以在它执行操作的同时拥有一个输出区域来复制数据和更改别名。

“ FC到FC”对话框,其中“属性”处于打开状态(从上下文菜单中)

在python中,该field_map部分的语法很棘手,因此请以交互方式遍历一下,以将参数设置为直线,然后使其运行。然后转到结果窗口,右键单击并复制python snippet。这是一个重新组合为更易于扩展和重复使用的代码段(可以做更多工作来分解字段图和属性的各个部分):

inFC = 'e:/Canvec/fix.gdb/HD_1480009_2'
outFC = 'HD_with_aliases'
out_wspace = 'e:/canvec/fix.gdb'
where_clause = '#'      # use default
config_keyword = '#'    #    "

# build field map
fmap_out_att = 'CODE /\Specification code/\ '  # field and alias name
fmap_properties = 'true true false 4 Long 0 0 ,First,#,'  # field properties
fmap_in_att = 'e:/Canvec/fix.gdb/HD_1480009_2,CODE,-1,-1'  # input FC and field

# construct the complete field map
field_map = fmap_out_att + fmap_properties + fmap_in_att
   # results in:
   # "CODE /\Specification code/\ true true false 4 Long 0 0 ,First,#,e:/Canvec/fix.gdb/HD_1480009_2,CODE,-1,-1"


arcpy.FeatureClassToFeatureClass_conversion(inFC, out_wspace, outFC, 
        where_clause, field_map, config_keyword)

# the template command copied from Results window, used for building above
# arcpy.FeatureClassToFeatureClass_conversion("e:/Canvec/fix.gdb/HD_1480009_2","e:/canvec/fix.gdb","HD_with_aliases3","#","CODE /\Specification code/\ true true false 4 Long 0 0 ,First,#,e:/Canvec/fix.gdb/HD_1480009_2,CODE,-1,-1","#")

2

该解决方案适用于使用SQL Server作为地理数据库的用户。您可以通过SQL更新命令手动更改它。所有功能的名称均保存在[sde]。[GDB_OBJECTCLASSES]表中。仅在更改别名列值时才设置别名。

UPDATE [sde].[sde].[GDB_OBJECTCLASSES] 
SET AliasName = 'an alias name' 
WHERE Name='your feature class name'

编辑:此方法是更改​​别名的快速方法。但是使用IClassSchemaEdit更好,因为在sql更新方法中,直到重置功能工作区之前,您才能使用别名。

Public Sub SetAliasName(FeatureClass As IFeatureClass, AliasName As String)
        Dim abjTable As ITable = FeatureClass
        Dim objClass As IObjectClass = abjTable
        Dim edit As IClassSchemaEdit = objClass
        edit.AlterAliasName(AliasName)
End Sub

1
现在很明显,我想一想!使用个人GDB(Access .mdb)或任何RDBMS存储选项,也应该可以使用相同的方法。
马特·威尔基

为了在其他RDBMS中找到它,我认为最好从RDBMS复制备份,然后通过ArcCatalog更改别名,然后将当前数据库与备份进行比较,您可以看到更改并找出别名保存在何处。
Mehdi 2015年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.