gpt4 book ai didi

python - UnicodeEncodeError 与 xlrd

转载 作者:太空宇宙 更新时间:2023-11-04 01:03:35 24 4
gpt4 key购买 nike

我正在尝试使用 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。

最佳答案

'ascii' codec can't encode

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

Documentation reference:

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()).

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

关于python - UnicodeEncodeError 与 xlrd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31661769/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com