python - 这是什么编码以及如何在 Python 中解码它?

标签 python python-3.x unicode

我有一个包含 %ed%a1%85%ed%b7%97.svg 的文件名,并且想要将其解码为 Python 3 中正确的字符串表示形式。我知道结果将是𡗗.svg 但以下代码不起作用:

import urllib.parse
import codecs

input = '%ed%a1%85%ed%b7%97.svg'
unescaped = urllib.parse.unquote(input)
raw_bytes = bytes(unescaped, "utf-8")
decoded = codecs.escape_decode(raw_bytes)[0].decode("utf-8")
print(decoded)

将打印������.svg。但是,当 input 是像 %e8%b7%af.svg 这样的字符串时,它会正确解码为 路.svg 。 >.

我尝试使用在线工具(例如https://mothereff.in/utf-8)对其进行解码将 % 替换为 \x ,得到 \xed\xa1\x85\xed\xb7\x97.svg。该工具正确地将此输入解码为 𡗗.svg

这里发生了什么?

最佳答案

您需要正确的编码才能让命令行控制台/终端(支持并配置为 utf-8)显示正确的字符

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
PEP 263 -- Defining Python Source Code Encodings: https://www.python.org/dev/peps/pep-0263/
https://stackoverflow.com/questions/3883573/encoding-error-in-python-with-chinese-characters#3888653
"""
from urllib.parse import unquote

urlencoded = '%ed%a1%85%ed%b7%97'

char = unquote(urlencoded, encoding='gbk')
char1 = unquote(urlencoded, encoding='big5_hkscs')
char2 = unquote(urlencoded, encoding='gb18030')

print(char)
print(char1)
print(char2)

# 怼呿窏
# 瞴�窾�
# 怼呿窏

这是一个非常奇特的unicode字符,我对编码错误,它不是简体中文字符,它是传统字符,并且在映射中也很远 \U215D7 - CJK UNIFIED IDEOGRAPHS EXTENSION B .
但列出的代码点和其他值让我怀疑这是一个编码不良的代码,所以我花了一段时间。
有人帮助我弄清楚编码是如何达到这种形式的。您需要进行一些编码转换才能将其恢复为原始值。

cjk = unquote_to_bytes(urlencoded).decode('utf-8', 'surrogatepass').encode('utf-16', 'surrogatepass').decode('utf-16')
print(cjk) 

关于python - 这是什么编码以及如何在 Python 中解码它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52913575/

相关文章:

python - 属性错误: type object 'Callable' has no attribute '_abc_registry'

Python Pandas Dataframe 过滤器不起作用

python - Pymongo 游标迭代的替代方案

C++:具有多种语言的字符串

python - 我怎样才能用 python 的枕头使我裁剪的 gif 角透明?

json - 如何打开和读取 JSON 文件?

python - 动态创建一个类而不实例化它 - 没有元类?

python - pymssql utf8 : queries with back slash

c++ - (C++) 在 Windows CMD 中显示阴影 block (↓、▒、░)

python - 如何解决 PyMongo 在查询中首先放置 MongoDB 分数并导致错误的问题