Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将文件转换为Ascii正在引发异常_Python_Python 3.x_Unicode - Fatal编程技术网

Python 将文件转换为Ascii正在引发异常

Python 将文件转换为Ascii正在引发异常,python,python-3.x,unicode,Python,Python 3.x,Unicode,因此,我将其编码为: def ConvertFileToAscii(args, filePath): try: # Firstly, make sure that the file is writable by all, otherwise we can't update it os.chmod(filePath, 0o666) with open(filePath, "rb") as file: contentOf

因此,我将其编码为:

def ConvertFileToAscii(args, filePath):
    try:
       # Firstly, make sure that the file is writable by all, otherwise we can't update it
        os.chmod(filePath, 0o666)

        with open(filePath, "rb") as file:
            contentOfFile = file.read()

        unicodeData = contentOfFile.decode("utf-8")
        asciiData = unicodeData.encode("ascii", "ignore")

        asciiData = unicodedata.normalize('NFKD', unicodeData).encode('ASCII', 'ignore')

        temporaryFile = tempfile.NamedTemporaryFile(mode='wt', delete=False)
        temporaryFileName = temporaryFile.name

        with open(temporaryFileName, 'wb')  as file:
            file.write(asciiData)

        if ((args.info) or (args.diagnostics)):
            print(filePath + ' converted to ASCII and stored in ' + temporaryFileName)


        return temporaryFileName

    #
    except KeyboardInterrupt:
        raise

    except Exception as e:
        print('!!!!!!!!!!!!!!!\nException while trying to convert ' + filePath + ' to ASCII')
        print(e)
        exc_type, exc_value, exc_traceback = sys.exc_info()
        print(traceback.format_exception(exc_type, exc_value, exc_traceback))

        if args.break_on_error:
            sys.exit('Break on error\n')
当我运行它时,会出现如下异常:

['Traceback (most recent call last):
', '  File "/home/ker4hi/tools/xmlExpand/xmlExpand.py", line 99, in ConvertFileToAscii
    unicodeData = contentOfFile.decode("utf-8")
    ', "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 1081: invalid start byte"]
我做错了什么

我真的不关心将它们转换为ASCII的数据丢失

ox9C是一个带有变音符号(Umlaut)的U,没有它我可以生活

如何将这些文件转换为仅包含纯Ascii字符?我真的需要将它们作为二进制打开并检查每个字节吗?

使用:

contentOfFile.decode('utf-8', 'ignore')

例外情况是在解码阶段,您没有忽略错误。

0x00f6
是在
ISO-8859-1
中编码的
o
(ouml)。我猜你用错了Unicode解码器


尝试:
unicodeData=contentOfFile.decode(“ISO-8859-1”)

您不需要将整个文件加载到内存中并调用
.decode()
open()
具有
encoding
参数(在Python 2上使用
io.open()
):

如果您需要Unicode文本的ascii音译;考虑一下,

我真的不关心将它们转换为ASCII的数据丢失。 ... 如何将这些文件转换为仅包含纯Ascii字符

一种方法是使用
解码
方法的替换选项。replace优于ignore的优点是,可以为缺少的值获取占位符,这有助于防止对文本的误解

确保使用ASCII编码而不是UTF-8。否则,解码器尝试重新同步时,可能会丢失相邻的ASCII字符

最后,在解码步骤后运行
encode('ascii')
。否则,将留下一个unicode字符串而不是字节字符串

>>> string_of_unknown_encoding = 'L\u00f6wis'.encode('latin-1')
>>> now_in_unicode = string_of_unknown_encoding.decode('ascii', 'replace')
>>> back_to_bytes = now_in_unicode.replace('\ufffd', '?').encode('ascii')
>>> type(back_to_bytes)
<class 'bytes'>
>>> print(back_to_bytes)
b'L?wis'
>>未知编码的字符串='L\u00f6wis'。编码('latin-1')
>>>现在\u in\u unicode=编码未知的字符串\u。解码('ascii','replace')
>>>返回到unicode中的当前字节。替换('\ufffd','?')。编码('ascii'))
>>>类型(返回到字节)
>>>打印(返回到字节)
b'L?wis'
也就是说,没错™ 要做到这一点,就要开始关注数据丢失并使用正确的编码(很明显,您的输入不是UTF-8格式的,否则解码就不会失败):

>>已知拉丁语编码的字符串='L\u00f6wis'。编码('latin-1')
>>>现在,unicode中的字符串=已知拉丁1编码的字符串
>>>返回到字节=现在使用unicode.encode('ascii','replace')
>>>类型(返回到字节)
>>>打印(返回到字节)

Intresting。它似乎无法与1081的字节一起工作-可能需要检查其中的内容(如果1080是EOF,这可能是utf读取器期望一个开始字节的一个很好的理由。此外,如果之前的一个字节的转换不能正常工作,它可能会影响这个字节)。这个答案是正确的,但在很多方面都是错误的;-)输出是unicode而不是ASCII字节。此外,请求忽略“ascii”解码错误,而不是“utf-8”解码错误。一般来说,“替换”比“忽略”更容易理解输出。如果可能的话,更好的策略是尝试找出原始编码,而不是坚持使用已知的错误编解码器进行解码。
>>> string_of_unknown_encoding = 'L\u00f6wis'.encode('latin-1')
>>> now_in_unicode = string_of_unknown_encoding.decode('ascii', 'replace')
>>> back_to_bytes = now_in_unicode.replace('\ufffd', '?').encode('ascii')
>>> type(back_to_bytes)
<class 'bytes'>
>>> print(back_to_bytes)
b'L?wis'
>>> string_of_known_latin1_encoding = 'L\u00f6wis'.encode('latin-1')
>>> now_in_unicode = string_of_known_latin1_encoding.decode('latin-1')
>>> back_to_bytes = now_in_unicode.encode('ascii', 'replace')
>>> type(back_to_bytes)
<class 'bytes'>
>>> print(back_to_bytes)