【问题标题】:UnicodeEncodeError with xlrd带有 xlrd 的 UnicodeEncodeError
【发布时间】:2015-07-27 19:36:48
【问题描述】:

我正在尝试使用 xlrd 读取 .xlsx。我已经完成了一切设置和工作。它适用于具有普通英文字母和数字的数据。然而,当它到达瑞典字母(ÄÖÅ)时,它给了我这个错误:

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。

【问题讨论】:

  • 只是猜测,试试 - # -*- coding: utf-8 -*- ,而不是 cp1252
  • # coding... 指令/注释只影响 Python 如何读取 源代码本身,而不会影响其运行方式

标签: python unicode xlrd unicode-string


【解决方案1】:

'ascii' 编解码器无法编码

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

Documentation reference:

字符编码取决于平台。在 Windows 下,如果流是交互式的(也就是说,如果它的 isatty() 方法返回 True),则使用控制台代码页,否则使用 ANSI 代码页。在其他平台下,使用 locale 编码(参见 locale.getpreferredencoding())。

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

【讨论】:

  • 那么解决方案是什么?
  • 在运行 python 时将 PYTHONIOENCODING 环境变量设置为合适的值。您指定的编码需要能够表示您要输出的字符,并且它还需要与终端或控制台或 IDE 或任何连接程序输出的地方所期望的编码相匹配。
【解决方案2】:

xlrd 默认使用 Unicode 编码。如果 xlrd 无法识别编码,则会认为 excel 文件中使用的编码是 ASCII,字符编码。最后,如果编码不是 ASCII,或者如果 python 无法将数据转换为 Unicode,那么它将引发 UnicodeDecodeError。

别担心,我们有解决此类问题的方法。看来您正在使用cp1252。因此,虽然您将使用 open_workbook() 打开文件,但您可以按如下方式调用它:

>>> book = xlrd.open_workbook(filename='filename',encoding_override="cp1252")

当您将使用上述函数时,xlrd 将解码相应的编码,您就可以开始了。
来源:

  1. Standard Encodings.
  2. xlrd official documentation
  3. UnicodeDecodeError

【讨论】:

    【解决方案3】:

    在打印前尝试使用utf-8 作为建议的@Anand S Kumardecode 字符串。

    # -*- coding: utf-8 -*-
    import xlrd
    
    file_location = "test.xlsx"
    
    workbook = xlrd.open_workbook(file_location)
    sheet = workbook.sheet_by_index(0)
    
    cells = [sheet.cell_value(1, i).decode('utf-8') for i in range(2, 6)]
    print ' '.join(cells)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 2022-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-03
      • 1970-01-01
      相关资源
      最近更新 更多