Python:UnicodeEncodeError:' ascii'编解码器不能对字符u' \ xf1'进行编码。位置78:序数不在范围内(128)

时间:2017-03-23 03:57:56

标签: python

我尝试了两种解决此问题的方法,但会导致另一个错误。首先尝试encode,另一个尝试strip(#),假设这个错误中存在问题:

"color":rcolor,"text_color":tcolor})
File "/usr/lib/python2.7/csv.py", line 152, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 78: ordinal not in range(128)

我的代码现在看起来像这样:

routes = db.routes.find()
    for route in routes:
        try:
            color = route["properties"]["color"]
            color = color.strip('#')
            print(color)

            tcolor = route["properties"]["tcolor"]
            tcolor = tcolor.strip('#')
            print(tcolor)
        except KeyError:
            color = "0000FF"
            tcolor = ""

        writer.writerow({"route_id":route["route_id"],
                   "agency_id":route["properties"]["agency_id"],...,
                   "route_color":color,"route_text_color":tcolor})

我不太确定为什么它会一直收到unicode错误......

1 个答案:

答案 0 :(得分:2)

在写入csv之前尝试解析你的dict以获得unicode值。

def convert(input):
    if isinstance(input, dict):
        return {convert(key): convert(value) for key, value in input.iteritems()}
    elif isinstance(input, list):
        return [convert(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input

if __name__ == "__main__":
    utf_route = convert(route)

因此,如果您在写入csv时收到错误,请尝试下面的

import codecs

with codecs.open("local/file1.csv", "w", encoding='utf8') as f:
    writer = csv.writer(f, delimiter=",")
    writer.writerow(data.keys())
    writer.writerow(data.values())