如何在Python中从unicodedjsonobject中提取字符串?

2024-06-16 15:47:19 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图解析带有符号和表情符号等Unicode的字符串时,出现以下错误:

UnicodeEncodeError: 'ascii' codec can't encode character '\U0001f33b' in position 19: ordinal not in range(128)

示例对象:

{"user":{"name":"\u0e2a\u0e31\u0e48\u0e07\u0e14\u0e48\u0e27\u0e19 \u0e2b\u0e21\u0e14\u0e44\u0e27 \u0e40\u0e14\u0e23\u0e2a\u0e41\u0e1f\u0e0a\u0e31\u0e48\u0e19\u0e21\u0e32\u0e43\u0e2b\u0e21\u0e48 \u0e23\u0e32\u0e04\u0e32\u0e40\u0e1a\u0e32\u0e46 \u0e2a\u0e48\u0e07\u0e17\u0e31\u0e48\u0e27\u0e44\u0e17\u0e22 \u0e44\u0e14\u0e49\u0e02\u0e2d\u0e07\u0e0a\u0e31\u0e27\u0e23\u0e4c\u0e08\u0e49\u0e32 \u0e2a\u0e19\u0e43\u0e08\u0e15\u0e34\u0e14\u0e15\u0e48\u0e2d\u0e2a\u0e2d\u0e1a\u0e16\u0e32\u0e21 Is it","tag":"XYZ"}}

我可以提取标记值,但无法提取名称值。你知道吗

这是我的密码:

dict = json.loads(json_data)
print('Tag - 'dict['user']['tag'])
print('Name - 'dict['user']['name'])

Tags: indictuseru0e32u0e2au0e23u0e2du0e07
1条回答
网友
1楼 · 发布于 2024-06-16 15:47:19

您可以用CSV文件格式保存数据,也可以用Excel打开。当您以这种方式打开一个文件时:open(filename, "w")那么您只能存储ASCII字符,但是如果您尝试以这种方式存储Unicode数据,您将得到UnicodeEncodeError。为了存储Unicode数据,需要用UTF-8编码打开文件。你知道吗

mydict = json.loads(json_data)  # or whatever dictionary it is...

# Open the file with UTF-8 encoding, most important step
f = open("userdata.csv", "w", encoding='utf-8')

f.write(mydict['user']['name'] + ", " + mydict['user']['tag'] + "\n")
f.close()

根据您拥有的数据随时更改代码。
就这样。。。你知道吗

相关问题 更多 >