Python 从特定字符串解码
Python decode from a specific string
有人给了我这个字符串:“Al Baţḩah”(这可能是一个阿拉伯名字),
并要求我将它(以及其他类似字符串的列表)翻译成 Python.
这 website 使用“UTF8 解码”操作将其转换为“Al Baţḩah”。我正在尝试在 Python 中做同样的事情,但这是我尝试过的和我的结果。大多数示例采用了一系列 unicode 字节。我尝试了“检测”以查看他给我的到底是什么。如果它已经是 UTF8,那么我不确定那个网站将它转换成什么。
import chardet
byte_string = b"\x61\x62\x63"
decoded_string = byte_string.decode("utf8")
print(decoded_string)
sourceText = "Al Baţḩah"
sourceTextBytes = bytes(sourceText, 'utf-8')
print(chardet.detect(sourceTextBytes))
decoded_string2 = sourceTextBytes.decode("utf")
print("Result2=", decoded_string2)
以上输出:
abc
{'encoding': 'utf-8', 'confidence': 0.9690625, 'language': ''}
Result2= Al Baţḩah
输出与输入相同。我试过 ascic、utf8 等...作为解码语句的参数。
第 2 部分 - 下面的解决方案不适用于另一个奇怪的部分(这些是同事购买的 ISO 文档中的细分名称。)
Gədəbəy
看起来像 mojibake 的经典案例——在本例中,它使用 latin1 进行解释,而它应该是 UTF-8:
>>> "Al Baţḩah".encode('latin1')
b'Al Ba\xc5\xa3\xe1\xb8\xa9ah'
>>> "Al Baţḩah".encode('latin1').decode('UTF-8')
'Al Baţḩah'
那些想要 copy/paste 进入程序而不是命令行的代码:
source_text = "Al Baţḩah"
print("source_text=", source_text)
encoded_source_text = source_text.encode('latin1')
decoded_text = encoded_source_text.decode('UTF-8')
print("decoded_text=", decoded_text)
有人给了我这个字符串:“Al Baţḩah”(这可能是一个阿拉伯名字), 并要求我将它(以及其他类似字符串的列表)翻译成 Python.
这 website 使用“UTF8 解码”操作将其转换为“Al Baţḩah”。我正在尝试在 Python 中做同样的事情,但这是我尝试过的和我的结果。大多数示例采用了一系列 unicode 字节。我尝试了“检测”以查看他给我的到底是什么。如果它已经是 UTF8,那么我不确定那个网站将它转换成什么。
import chardet
byte_string = b"\x61\x62\x63"
decoded_string = byte_string.decode("utf8")
print(decoded_string)
sourceText = "Al Baţḩah"
sourceTextBytes = bytes(sourceText, 'utf-8')
print(chardet.detect(sourceTextBytes))
decoded_string2 = sourceTextBytes.decode("utf")
print("Result2=", decoded_string2)
以上输出:
abc
{'encoding': 'utf-8', 'confidence': 0.9690625, 'language': ''}
Result2= Al Baţḩah
输出与输入相同。我试过 ascic、utf8 等...作为解码语句的参数。
第 2 部分 - 下面的解决方案不适用于另一个奇怪的部分(这些是同事购买的 ISO 文档中的细分名称。)
Gədəbəy
看起来像 mojibake 的经典案例——在本例中,它使用 latin1 进行解释,而它应该是 UTF-8:
>>> "Al Baţḩah".encode('latin1')
b'Al Ba\xc5\xa3\xe1\xb8\xa9ah'
>>> "Al Baţḩah".encode('latin1').decode('UTF-8')
'Al Baţḩah'
那些想要 copy/paste 进入程序而不是命令行的代码:
source_text = "Al Baţḩah"
print("source_text=", source_text)
encoded_source_text = source_text.encode('latin1')
decoded_text = encoded_source_text.decode('UTF-8')
print("decoded_text=", decoded_text)