UnicodeEncodeError 与 xlrd [英] UnicodeEncodeError with xlrd

查看:34
本文介绍了UnicodeEncodeError 与 xlrd的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 xlrd 读取 .xlsx.我已经准备好一切并开始工作.它适用于具有普通英文字母和数字的数据.但是,当它遇到瑞典字母 (ÄÖÅ) 时,它给了我这个错误:

I'm trying to read a .xlsx with xlrd. I have everything set up and working. It works for data with normal English letters as well as numbers. However when it gets to Swedish letters (ÄÖÅ) it gives me this error:

print str(sheet.cell_value(1, 2)) + " " + str(sheet.cell_value(1, 3)) + " " + str(sheet.cell_value(1, 4)) + " " + str(sheet.cell_value(1, 5))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xd6' in position 1: ordinal not in range(128)

我的代码:

# -*- coding: cp1252 -*-
import xlrd

file_location = "test.xlsx"

workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(0)

print str(sheet.cell_value(1, 2)) + " " + str(sheet.cell_value(1, 3)) + " " + str(sheet.cell_value(1, 4)) + " " + str(sheet.cell_value(1, 5))

我什至尝试过:

workbook = xlrd.open_workbook("test.xlsx", encoding_override="utf-8")

以及:

workbook = xlrd.open_workbook("test.xlsx", encoding="utf-8")

我在 Windows 7 64 位计算机上运行 Python 2.7.

I'm running Python 2.7 on a Windows 7 64-bit computer.

推荐答案

'ascii' 编解码器无法编码

'ascii' codec can't encode

这里的问题不是读取文件时的解码,而是打印所需的编码.您的环境将 ASCII 用于 sys.stdout,因此当您尝试打印任何无法以 ASCII 编码的 Unicode 字符时,您将收到该错误.

The problem here isn't the decode when reading the file, it is the encode necessary to print. Your environment is using ASCII for sys.stdout, and so when you try to print any Unicode characters that can't be encoded in ASCII you'll receive that error.

文档参考:

字符编码是平台相关的.在 Windows 下,如果流是交互式的(即,如果其 isatty() 方法返回 True),则使用控制台代码页,否则使用 ANSI 代码页.在其他平台下,使用语言环境编码(参见 locale.getpreferredencoding()).

The character encoding is platform-dependent. Under Windows, if the stream is interactive (that is, if its isatty() method returns True), the console codepage is used, otherwise the ANSI code page. Under other platforms, the locale encoding is used (see locale.getpreferredencoding()).

不过,在所有平台下,您都可以通过在启动 Python 之前设置 PYTHONIOENCODING 环境变量来覆盖此值.

Under all platforms though, you can override this value by setting the PYTHONIOENCODING environment variable before starting Python.

这篇关于UnicodeEncodeError 与 xlrd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆