UTF-16到Ascii忽略十进制值大于127的字符
||
我知道有很多解决此问题的方法,但我的观点很特殊,我可能会截断utf16数据,但必须尽最大努力处理转换,而解码和编码会因UnicodeDecodeError而失败。因此想出了以下python代码。
请让我知道您对我如何改进它们以进行更快处理的意见。
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
没有找到相关结果
已邀请:
3 个回复
傻零凰死授
还有一个\'ignore \'选项,它只会丢弃无法解码的字节:
尽管通常需要一个“容忍”错误编码文本的系统,但通常很难准确地定义在这些情况下的预期行为。您可能会发现提供“处理”错误编码文本的要求的人并没有完全掌握字符编码的概念。
桑娠贯涤
即如果它在代码单元中途被截断,则剪掉最后一个字节,然后再次执行。那应该使您回到有效的UTF-16字符串,而不必尝试自己实现解码器。
吞睫素