【发布时间】:2011-09-15 17:57:40
【问题描述】:
我知道这个问题有很多解决方案,但我的解决方案很奇怪,我可能会得到截断的 utf16 数据,但必须尽最大努力处理解码和编码将因 UnicodeDecodeError 失败的转换。于是想出了下面的python代码。 请让我知道您的 cmets 我如何改进它们以加快处理速度。
try:
# conversion to ascii if utf16 data is formatted correctly
input = open(filename).read().decode('UTF16')
asciiStr = input.encode('ASCII', 'ignore')
open(filename).close()
return asciiStr
except:
# if fail with UnicodeDecodeError, then use brute force
# to decode truncated data
try:
unicode = open(filename).read()
if (ord(unicode[0]) == 255 and ord(unicode[1]) == 254):
print("Little-Endian format, UTF-16")
leAscii = "".join([(unicode[i]) for i in range(2, len(unicode), 2) if 0 < ord(unicode[i]) < 127])
open(filename).close()
return leAscii
elif (ord(unicode[0]) == 254 and ord(unicode[1]) == 255):
print("Big-Endian format, UTF-16")
beAscii = "".join([(unicode[i]) for i in range(3, len(unicode), 2) if 0 < ord(unicode[i]) < 127])
open(filename).close()
return beAscii
else:
open(filename).close()
return None
except:
open(filename).close()
print("Error in converting to ASCII")
return None
【问题讨论】:
-
顺便说一句,
open(filename).close()是浪费时间 - 它再次打开文件,然后立即关闭新的文件句柄。