【发布时间】:2016-02-02 07:46:57
【问题描述】:
我想知道如何将 ISO-8859-2 (latin-2) 字符(我的意思是表示 ISO-8859-2 编码字符的整数或十六进制值)转换为 UTF-8 字符。
我需要在 python 中处理我的项目:
- 从串口接收十六进制值,这些值是以 ISO-8859-2 编码的字符。
- 解码它们,这是 - 从中获取“标准”python unicode 字符串。
- 准备并写入 xml 文件。
使用 Python 3.4.3
txt_str = "ąęłóźć"
txt_str.decode('ISO-8859-2')
Traceback (most recent call last): File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'decode'
主要问题仍然是为“解码”方法准备有效输入(它适用于 python 2.7.10,这就是我在这个项目中使用的那个)。如何从十进制值中准备有效的字符串,即 Latin-2 代码数字?
请注意,由于我使用的设备和通信协议的限制,从串口接收 utf-8 字符会非常复杂。
样本数据,应要求提供:
68632057
62206A75
7A647261
B364206F
20616775
777A616E
616A2061
6A65696B
617A20B6
697A7970
6A65B361
70697020
77F36469
62202C79
6E647572
75206A65
7963696C
72656D75
6A616E20
73726F67
206A657A
65647572
77207972
73772065
00000069
这是一些示例数据。 ISO-8859-2 被推入 uint32,每个 int 4 个字符。
管理拆箱的代码:
l = l[7:].replace(",", "").replace(".", "").replace("\n","").replace("\r","") # crop string from uart, only data left
vl = [l[0:2], l[2:4], l[4:6], l[6:8]] # list of bytes
vl = vl[::-1] # reverse them - now in actual order
要从十六进制字符串中获取整数值,我可以简单地使用:
int_vals = [int(hs, 16) for hs in vl]
【问题讨论】:
-
它应该很简单:this_is_the_text_string.decode('ISO-8859-2'),它为您提供 unicode 字符串(至少在 Python 3 中)。
-
简单。从hex to bytes、decode as latin-2、encode as UTF-8 转换。你有任何样本数据吗?
-
但是,如果您要编写 XML,为什么不将值保留为 Unicode(从 ISO-8859-2 解码),并将其留给 XML 库编码为 UTF-8?
-
Python 3 中的字符串类型是 Unicode。如果要输入原始单字节,请使用 Python 3 字节字符串数据类型;但是您需要将字节编码为十六进制,而不是字符(因为这些是 Unicode 字符)。
标签: python unicode utf-8 iso iso-8859-2