python将dict中的unicode打印成中文的方法

2023-05-19,,

这篇文章主要讲解了pythondict中的unicode打印成中文的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

我就废话不多说了,大家还是直接看代码吧!

import json
a = {u'content': {u'address_detail': {u'province': u'\u5409\u6797\u7701', u'city': u'\u957f\u6625\u5e02', u'street_number': u'', u'district': u'', u'street': u'', u'city_code': 53}, u'point': {u'y': u'43.89833761', u'x': u'125.31364243'}, u'address': u'\u5409\u6797\u7701\u957f\u6625\u5e02'}, u'status': 0, u'address': u'CN|\u5409\u6797|\u957f\u6625|None|CERNET|0|0'}
print json.dumps(a).decode('unicode-escape')

输出:

{"content": {"address_detail": {"province": "吉林省", "city": "长春市", "street_number": "", "district": "", "street": "", "city_code": 53}, "address": "吉林省长春市", "point": {"y": "43.89833761", "x": "125.31364243"}}, "status": 0, "address": "CN|吉林|长春|None|CERNET|0|0"}

补充知识:在python代码中输出一个字符的unicode编码

如果ch是一个unicode字符:

print '\u%04x' % ord(ch)

ord(ch)返回的是这个字符的unicode编码的10进制形式,只需要将其按照unicode的格式用16进制打印出来即可

例如:

上面这个例子中就打印出了"你"、"好"、"a"这三个unicode字符的unicode码。

unicode字符就是unicode字符串中的字符,对于字符串常量来说,以u为前缀的是unicode字符串;

如果一个是从utf-8文本文件中读取的一行str,转换过为unicode字符串只需要decode即可:

line = myfile.readline()
uniline = line.decode('utf-8')

//此时uniline就是unicode字符串了,如果是gbk格式的文件,则要用gbk编码来decode

看完上述内容,是不是对python将dict中的unicode打印成中文的方法有进一步的了解,如果还想学习更多内容,欢迎关注本站行业资讯频道。

《python将dict中的unicode打印成中文的方法.doc》

下载本文的Word格式文档,以方便收藏与打印。