答案实际上很简单:一旦从文件中读取数据,就使用文件的编码将其转换为unicode,并处理UnicodeDecodeError异常:
try:
# decode using utf-8 (use ascii if you want)
unicode_data = str_data.decode("utf-8")
except UnicodeDecodeError, e:
print "The error is there !"
这将使您免于许多麻烦;您不必担心多字节字符编码,并且外部库(包括xlwt)仅在需要编写“正确的东西”时才做。
Python 3.0将强制要求指定字符串的编码,因此现在开??始这样做是个好主意。