我有一個 utf-8 編碼物件的串列,例如:
test = [b'{"abc\xf0\x9f\x94\xa5\xf0\x9f\x91\xbd\xf0\x9f\xa7\x83": 123}',
b'{"abc\xf0\x9f\xa7\x83": 234}']
并將其解碼如下:
result = list(map(lambda x: json.loads(x.decode('utf-8','ignore')),test))
我注意到一些表情符號沒有按預期轉換,如下所示:
[{'abc????\U0001f9c3': 123}, {'abc\U0001f9c3': 234}]
但是,當我解碼單個字串時,會得到預期的輸出:
print(b"abc\xf0\x9f\x94\xa5\xf0\x9f\x91\xbd\xf0\x9f\xa7\x83".decode('utf-8'))
abc??????
我不確定為什么使用 json.loads 的第一種方法會產生意外的輸出。有人可以提供任何指示嗎?
uj5u.com熱心網友回復:
在json.loads()列印串列之后。串列使用參考 Unicode 表的字串 ( repr()) 的除錯表示來確定代碼點是否可列印。如果未知,您會在串列顯示中獲得轉義碼。 一個字串直接查看沒有轉義碼print的字串 ( ) 的“用戶友好”表示。str()
U 1F9C3 飲料盒是在Unicode 12.0中添加的。Python 3.7 使用Unicode 11.0定義,這就是您看到轉義碼的原因。Python 3.8 使用 Unicode 12.1,更新后的表格表明該字符是可列印的。如果您的終端支持該字符并且使用了適當的字體,它將顯示。
例如,我使用的 Python 3.10 下面支持 Unicode 13.0。U 1F978 在Unicode 13.0中定義,但 U 1F979 在Unicode 14.0中添加。您的瀏覽器可能會或可能不會顯示實際的表情符號,具體取決于瀏覽器 Unicode 支持和使用的字體(Chrome 99 沒有)。如果不是,則列印替換字符。repr()這仍然演示了字串的顯示和str()使用的區別print:
>>> s = '\U0001f978\U0001f979'
>>> s # The REPL shows the repr (debug) representation
'??\U0001f979'
>>> print(repr(s)) # forcing print to use the repr as well.
'??\U0001f979'
>>> [s] # repr() is also used for list content.
['??\U0001f979']
>>> print(s) # no escape codes here.
????
>>> print(ascii(s)) # forcing all non-ASCII to escape codes
'\U0001f978\U0001f979'
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/443562.html
