ArcGIS字段计算器中的语法错误



我在ArcGIS中得到了一个小脚本,它创建了一个超链接。

我代码:

def Befahrung(value1, value2):
    if value1 is '':
        return ''
    else:
        return "G:\Example\" + str(value1) + "\File_" + str(value2) + ".pdf"

错误(仅当!Bezeichnun!包含特殊字符时):

ERROR 000539: Error running expression: Befahrung(u" ",u"1155Mönch1")
Traceback (most recent call last):
  File "<expression>", line 1 in <module>
  File "<string>", line 5 in Befahrung
UnicodeEncodeError: 'ascii' codec can't encode character u'xf6' in position 5: ordinal not in range(128)

!Bezeichnun!!Auftrag!都是字符串。在!Bezeichnun!包含一个特殊字符之前,它工作得很好。我不能更改字符,我需要保存它们。

我需要改变什么?

Befahrung中,您将字符串(在本例中为Unicode)转换为ASCII:

str(value1);
str(value2);

不能工作,如果value1value2包含非ascii字符。你想使用

unicode(value1)

或者更好,使用字符串格式:

return u"G:\Example\{}\File_{}.pdf".format(value1, value2)

(适用于Python 2.7及以上版本)

我推荐阅读Python Unicode HOWTO。错误可以被压缩到

>>> str(u"1155Mönch1")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'xf6' in position 5: ordinal not in range(128)

如果你知道你需要什么字符编码(例如,UTF-8),你可以这样编码

value1.encode('utf-8')

最新更新