【问题标题】:Converting from utf-16 to utf-8 in Python 3在 Python 3 中从 utf-16 转换为 utf-8
【发布时间】:2011-03-09 13:47:39
【问题描述】:

我正在使用 Python 3 进行编程,但遇到了一个小问题,我在网上找不到任何相关参考。

据我了解,默认字符串是 utf-16,但我必须使用 utf-8,我找不到将从默认字符串转换为 utf-8 的命令。 非常感谢您的帮助。

【问题讨论】:

    标签: python utf-8 character-encoding python-3.x utf-16


    【解决方案1】:

    在 Python 3 中,当您使用字符串操作时,有两种不同的数据类型很重要。首先是字符串类,一个代表 unicode 代码点的对象。重要的是,这个字符串不是一些字节,而是一个字符序列。其次是 bytes 类,它只是一个字节序列,通常表示存储在编码中的字符串(如 utf-8 或 iso-8859-15)。

    这对您意味着什么?据我了解,您想读取和写入 utf-8 文件。让我们编写一个程序,将所有 'ć' 替换为 'ç' 字符

    def main():
        # Let's first open an output file. See how we give an encoding to let python know, that when we print something to the file, it should be encoded as utf-8
        with open('output_file', 'w', encoding='utf-8') as out_file:
            # read every line. We give open() the encoding so it will return a Unicode string. 
            for line in open('input_file', encoding='utf-8'):
                #Replace the characters we want. When you define a string in python it also is automatically a unicode string. No worries about encoding there. Because we opened the file with the utf-8 encoding, the print statement will encode the whole string to utf-8.
                print(line.replace('ć', 'ç'), out_file)
    

    那么什么时候应该使用字节?不经常。我能想到的一个例子是当您从套接字读取某些内容时。如果你在一个字节对象中有这个,你可以通过执行 bytes.decode('encoding') 将它变成一个 unicode 字符串,反之亦然使用 str.encode('encoding')。但如前所述,您可能不需要它。

    不过,因为它很有趣,这里是艰难的方式,您自己编码所有内容:

    def main():
        # Open the file in binary mode. So we are going to write bytes to it instead of strings
        with open('output_file', 'wb') as out_file:
            # read every line. Again, we open it binary, so we get bytes 
            for line_bytes in open('input_file', 'rb'):
                #Convert the bytes to a string
                line_string = bytes.decode('utf-8')
                #Replace the characters we want. 
                line_string = line_string.replace('ć', 'ç')
                #Make a bytes to print
                out_bytes = line_string.encode('utf-8')
                #Print the bytes
                print(out_bytes, out_file)
    

    关于这个主题(字符串编码)的好读物是http://www.joelonsoftware.com/articles/Unicode.html。真心推荐阅读!

    来源:http://docs.python.org/release/3.0.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit

    (PS如你所见,我在这篇文章中没有提到utf-16。我实际上不知道python是否使用它作为内部解码,但这完全无关紧要。目前你正在使用一个字符串,你使用字符(代码点),而不是字节。

    【讨论】:

    • Python 确实使用 UTF-16 作为 Windows 上的内部编码。在 Linux 上,它使用 UTF-32。
    • 嗨,感谢您的回答。 Dan04 你知道我怎样才能告诉它只使用 utf-8 吗?
    • @idan 你为什么想要那个?无论如何,除非您自己修改和重新编译 Python,否则这是不可能的......
    • 我想要这个,因为我必须使用一个标记器,它给我 utf-8 中的单词,我不确定是否,让我们检查一个由 py​​thon 定义的字符,例如 'א ' (一个希伯来字符)它将正确地与它的单词进行比较。你明白我说的了吗?
    • 这是 Python 中的分词器吗?然后只需将字节 utf-8 转换为 unicode 字符串,比较就会正常工作。无需猜测或不确定编码。只需检查您拥有的东西并使用我的回答中提到的方法就可以了。
    猜你喜欢
    • 1970-01-01
    • 2015-09-21
    • 2013-02-25
    • 2015-09-19
    • 2017-09-24
    • 1970-01-01
    • 2021-01-30
    • 2010-10-19
    相关资源
    最近更新 更多