Python之encoding

encoding

根据Python官方文档中有关字符串的部分1

str.encode(encoding=”utf-8”, errors=”strict”)
Return an encoded version of the string as a bytes object. Default encoding is ‘utf-8’. errors may be given to set a different error handling scheme. The default for errors is ‘strict’, meaning that encoding errors raise a UnicodeError. Other possible values are ‘ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.

encoding是编码的意思,在python中,Unicode类型是作为编码的基础类型。

Unicode

Unicode是一种标准,包括了字符集、编码方案等。因为ASCII码只能编码英文字符,具有很大的局限性,而Unicode 为每种语言中的每个字符设定了统一并且唯一的二进制编码,以满足跨语言、跨平台进行文本转换、处理的要求2。在https://unicode-table.com/en/可以查到所有的Unicode字符。

utf-8

UTF-8以字节为单位对Unicode进行编码。

utf-16

UTF-16编码以16位无符号整数为单位。

utf-32

UTF-32编码以32位无符号整数为单位。

gbk

GBK全称《汉字内码扩展规范》(GBK即“国标”、“扩展”汉语拼音的第一个字母,英文名称:Chinese Internal Code Specification)3。GBK是采用单双字节变长编码,英文使用单字节编码,完全兼容ASCII字符编码,中文部分采用双字节编码。

ASCII 码

ASCII 码使用指定的7 位或8 位二进制数组合来表示128 或256 种可能的字符4

decoding

根据Python官方文档中有关字符串的部分1

bytes.decode(encoding=”utf-8”, errors=”strict”)
bytearray.decode(encoding=”utf-8”, errors=”strict”)
Return a string decoded from the given bytes. Default encoding is ‘utf-8’. errors may be given to set a different error handling scheme. The default for errors is ‘strict’, meaning that encoding errors raise a UnicodeError. Other possible values are ‘ignore’, ‘replace’ and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.
Note Passing the encoding argument to str allows decoding any bytes-like object directly, without needing to make a temporary bytes or bytearray object.

decode()就是将“字节流”按照某种规则转换成“文本”,可以理解为是encode()的逆过程。

例子

现在用一个小小的例子来体验一下编码和解码。
首先可以去https://learnpythonthehardway.org/python3/languages.txt上将上面的字符保存在一个txt文件中,并以utf-8的形式保存,命名为languages。写下代码:

#####encoding&decoding#####
def main(file,encoding,errors):
    line = file.readline()
    if line:
        print_file(line,encoding,errors)
        return main(file,encoding,errors)

def print_file(line,encoding,errors):
    next_lang = line.strip() ###strip() 方法用于移除字符串头尾指定的字符(默认为空格)
    raw_bytes = next_lang.encode(encoding, errors=errors) ###encode()函数中errors默认为strict,还可以设置为ignore,replace等
    cooked_string = raw_bytes.decode(encoding, errors=errors) ###decode()函数为解码

    print(raw_bytes, "<===>", cooked_string)


languages = open("languages.txt", encoding="utf-8")
main(languages,"utf-16","strict")

可以得到结果(如下只显示结果片段):
这里写图片描述
左边为utf-8编码结果,右边为原字符,两者一一对应且可以进行互逆运算。
将代码中的“utf-8”改成“utf-16”,可以得到以下结果:
这里写图片描述

### 回答1: Python中的open函数用于打开文件,可以指定文件的编码方式。如果不指定编码方式,则默认使用系统的编码方式。可以使用以下方式指定编码方式: 1. 使用encoding参数指定编码方式,例如: ``` f = open('file.txt', 'r', encoding='utf-8') ``` 2. 使用io库中的open函数,例如: ``` import io f = io.open('file.txt', 'r', encoding='utf-8') ``` 在读取文件时,需要使用相应的编码方式进行解码,例如: ``` content = f.read().decode('utf-8') ``` 在写入文件时,需要使用相应的编码方式进行编码,例如: ``` f.write(content.encode('utf-8')) ``` ### 回答2: 在Python中,open()函数是用于打开文件的一个内置函数。它允许我们在代码中访问并处理文件的内容。 open()函数有两个主要参数,一个是文件路径,另一个是文件模式。 文件路径可以是一个字符串,指定要打开的文件的位置。这可以是相对路径(相对于当前执行脚本的位置)或绝对路径(完整的文件路径)。 文件模式是用于定义文件操作的字符串。其中最常见的模式是'r',它表示以只读模式打开文件。其他常见的模式包括'w'(写入模式)和'a'(追加模式)。 此外,在open()函数中,我们还可以使用encoding参数来指定文件的编码方式。编码方式是用于将文件中的二进制数据转换为可读的字符的规则。在Python中,常用的编码方式包括UTF-8、GBK等。 例如,在使用open()函数打开一个文件时,我们可以通过传递encoding参数来指定文件的编码方式: file = open("example.txt", "r", encoding="UTF-8") 上述代码将以UTF-8编码方式打开名为example.txt的文件,并将其赋值给file变量。这样,我们就可以通过读取file变量来访问文件的内容。 总之,open()函数可以用来打开文件并指定文件的编码方式,以便我们可以在代码中读取和处理文件的内容。 ### 回答3: 在Python中,open()函数用于打开一个文件并返回对应的文件对象。它具有第二个可选参数"encoding",用于指定文件的编码格式。 在文本文件的处理中,通常我们需要指定文件的编码格式,以便正确地读取和写入其中的文本内容。文件的编码格式取决于该文件中的字符如何被表示和存储。 当我们使用open()函数打开文件时,可以通过在参数中指定"encoding"来指定文件的编码格式。常用的编码格式包括utf-8、gbk等。例如,如果我们要打开一个utf-8编码的文件,可以使用以下方式: ```python file = open("filename.txt", "r", encoding="utf-8") ``` 这样,返回的文件对象file就是按照utf-8编码格式打开的。我们可以通过file对象来读取和操作文件中的内容。 同样地,当我们要写入一个新的文本文件时,也可以指定文件的编码格式。例如,如果我们要写入一个utf-8编码的文件,可以使用以下方式: ```python file = open("newfile.txt", "w", encoding="utf-8") ``` 这样,我们就可以使用file对象的写入方法来向文件中写入文本内容。 总之,Python中的open()函数的"encoding"参数允许我们指定文件的编码格式,以便正确地读取和写入文本内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值