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
    
已邀请:
        为了容忍错误,您可以对字节字符串的解码方法使用可选的第二个参数。在此示例中,悬空的第三个字节(\'c \')被替换为\“替换字符\” U + FFFD:
>>> \'abc\'.decode(\'UTF-16\', \'replace\')
u\'\\u6261\\ufffd\'
还有一个\'ignore \'选项,它只会丢弃无法解码的字节:
>>> \'abc\'.decode(\'UTF-16\', \'ignore\')
u\'\\u6261\'
尽管通常需要一个“容忍”错误编码文本的系统,但通常很难准确地定义在这些情况下的预期行为。您可能会发现提供“处理”错误编码文本的要求的人并没有完全掌握字符编码的概念。     
        关于什么:
data = open(filename).read()
try:
    data = data.decode(\"utf-16\")
except UnicodeDecodeError:
    data = data[:-1].decode(\"utf-16\")
即如果它在代码单元中途被截断,则剪掉最后一个字节,然后再次执行。那应该使您回到有效的UTF-16字符串,而不必尝试自己实现解码器。     
        这只是我的“最佳实践”改进而已。文件访问实际上应该包裹在4个块中。这将为您处理打开和清理操作。     

要回复问题请先登录注册