【发布时间】:2016-03-07 17:26:39
【问题描述】:
我正在解析 csv,并使用 xlwt 将其部分内容写入 xls 文件
每次在原始文件中弹出 µs 时,我都会从xlwt 收到一个 UnicodeDecodeError:
File "C:\SW_DevSandbox\E2\FlightTestInstrumentation\ICDforFTI\ICDforFTI.py", line 243, in generateICD
icd.write(icdLine,icdTitle.index('Unit'),entry['Unit'])
File "C:\espressoE2\tools\OpenVIB\1.2\python\lib\site-packages\xlwt\Worksheet.py", line 1030, in write
self.row(r).write(c, label, style)
File "C:\espressoE2\tools\OpenVIB\1.2\python\lib\site-packages\xlwt\Row.py", line 240, in write
StrCell(self.__idx, col, style_index, self.__parent_wb.add_str(label))
File "C:\espressoE2\tools\OpenVIB\1.2\python\lib\site-packages\xlwt\Workbook.py", line 326, in add_str
return self.__sst.add_str(s)
File "C:\espressoE2\tools\OpenVIB\1.2\python\lib\site-packages\xlwt\BIFFRecords.py", line 24, in add_str
s = unicode(s, self.encoding)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb5 in position 0: invalid start byte
我认为根本问题如下:
在 python 3 中,我可以很容易地表示 µs:
>>> '\xb5s'
'µs'
>>>
在 python 2 中,显然不是:
>>> '\xb5s'
'\xb5s'
>>> u'\xb5s'
u'\xb5s'
>>> unicode('\xb5s')
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb5 in position 0: ordinal not in range(128)
>>> unicode('\xb5s','utf8')
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\espressoE2\tools\OpenVIB\1.2\python\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb5 in position 0: invalid start byte
>>>
编辑:print u'\xb5s' 在 Python 2 中工作,感谢 @cdarke。但是打印并不能解决问题,它不是我可以提供给xlwt 的内部表示。
编辑结束。
那么如何在 Python 2 中表示 µs?
Notepad++ 以 µs 显示 csv 文件。 “编码”菜单显示它的编码为“ANSI”,如果我更改为“UTF-8”,我开始在文本中看到“B5”。 Python 2 Unicode 没有称为“ANSI”的编码。 是否有与 Notepad++ 所称的“ANSI”等效的 Python 2 Unicode 编码?
【问题讨论】:
-
在 python 2.7 I
print u'\xb5s'上,它在 OS X 的终端中显示良好,因此它可能是终端系统使用的编码。您使用的是哪个环境?由于您使用的是 Windows,因此您应该知道cmd.exe不支持 Unicode。 -
@cdarke ´print u'\xb5s'´ 也适用于我的 python 2,感谢您提供的线索。我最初的尝试没有使用 print 语句。
-
“ANSI”编码可能是“Windows-1252”。尝试使用
'cp1252'编码,如果它没有帮助'latin_1'。 -
@Nikita icdWorkbook = xlwt.Workbook(encoding="cp1252") 成功了。谢谢。
标签: python python-2.7 unicode encoding