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!
里有了特殊字符。我不能改变这些字符,我需要保留它们。
我需要改什么呢?
2 个回答
2
在Befahrung
中,你需要把一个字符串(这里是Unicode格式)转换成ASCII格式:
str(value1);
str(value2);
如果value1
或value2
里面有非ASCII字符,这样的转换就会失败。你可以使用
unicode(value1)
或者更好的是,使用字符串格式化:
return u"G:\\Example\\{}\\File_{}.pdf".format(value1, value2)
(这个方法在Python 2.7及以上版本中有效)
2
我建议你去看看这个Python Unicode 使用指南。这个错误可以简单理解为
>>> 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')