python - ascii 编解码器无法对超出范围的字符 u'\u2019' 进行编码(128)

标签 python unicode encoding arcgis arcpy

Python 2.6,升级不是一个选择

脚本旨在从 arcgis 数据库中获取字段并创建将 Oracle 语句插入到文本文件中以供以后使用。 3000 条记录后有 7500 条记录出错,并指出问题所在。

fieldValue = unicode(str(row.getValue(field.name)),'utf-8',errors='ignore')

我已经尝试了unicode和encode的几乎所有变体。我是 python 新手,真的只需要有经验的人来查看我的代码并找出问题所在。

import arcpy

#Where the GDB Table is located
fc = "D:\GIS Data\eMaps\ALDOT\ALDOT_eMaps_SignInventory.gdb/SignLocation"

fields = arcpy.ListFields(fc)
cursor = arcpy.SearchCursor(fc)

#text file output
outFile = open(r"C:\Users\kkieliszek\Desktop\transfer.text", "w")


#insert values into table billboard.sign_inventory
for row in cursor:
 outFile.write("Insert into billboard.sign_inventory() Values (") 
 for field in fields:

    fieldValue = unicode(str(row.getValue(field.name)),'utf-8',errors='ignore')

    if row.isNull(field.name) or fieldValue.strip() == "" : #if field is Null or a Empty String print NULL
        value = "NULL"
        outFile.write('"' + value + '",')
    else: #print the value in the field
        value = str(row.getValue(field.name))
        outFile.write('"' + value + '",')

outFile.write("); \n\n ")


outFile.close()    # This closes the text file

错误代码:

Traceback (most recent call last):
 File "tablemig.py", line 25, in <module>
  fieldValue = unicode(str(row.getValue(field.name)),'utf-8',errors='ignore')
 UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in    position 76: ordinal not in range(128)

最佳答案

永远不要在 unicode 对象上调用 str():

>>> str(u'\u2019')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 0: ordinal not in range(128)

要以 csv 格式写入包含 Unicode 字符串的行,请使用 UnicodeWriter而不是手动格式化字段。它应该一次解决几个问题。

关于python - ascii 编解码器无法对超出范围的字符 u'\u2019' 进行编码(128),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32747648/

相关文章:

c# - 在 C# 中编码 XML

c#、Excel + csv : how to get the correct encoding?

python - 更改 pandas 数据框的列类型 - 查找阻止转换的违规行

python - B 列中具有匹配 A 列值的行的总和值

python - beforeTest 方法中的单元测试 __unittest_skip__ 访问

Mysql 使用 utf8 varchar 字段查找不正确

unicode - 未映射到 Unicode 代码点的名称示例

Java获取字符的十进制字节表示

Python 和 C IPC

python - 格式化 Unicode 的 Unicode 表示?