练习代码
import sys
script, encoding, errors = sys.argv
def main(language_file, encoding, errors):
line = language_file.readline()
if line:
print_line(line, encoding, errors)
return main(language_file, encoding, errors)
def print_line(line, encoding, errors):
next_lang = line.strip()
raw_bytes = next_lang.encode(encoding, errors = errors)
cooked_string = raw_bytes.decode(encoding, errors = errors)
print(raw_bytes, "<===>", cooked_string)
languages_file = open("languages.txt", encoding = "utf-8")
main(languages_file, encoding, errors)
补充
-
encode
和decode
互为逆操作,encode
是将字符串中的字符都转化为encoding
属性指定的编码,转化后的又叫raw string
。
-
errors
属性制定的是编码错误后的操作方式,有很多值:strict
是报UnicodeError
错误;ignore
是忽略;replace
是指替代正确部分。
网友评论