使用Python请求解码中文字符

2024-09-26 21:42:44 发布

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

我在用新闻API.org试图拉中文文章。当我打印出来的时候,它好像看不懂汉字。而是显示u'\u8fdd\u89c4。在

{u'articles': [{u'author': u'chinanews',
                u'description': u'\u8fdd\u89c4 \u539f\u6599\u836f\u5904\u65b9\u836f\u6d41\u5165\u5e02\u573a\u3000\u3000\u5206\u6790\u5404\u5730\u8b66\u65b9\u516c\u5e03\u7684\u5236\u552e\u6709\u6bd2\u6709\u5bb3\u4fdd\u5065\u54c1\u6848\u60c5\u4e0d\u96be\u53d1\u73b0\uff0c\u8fd9\u4e9b\u6709\u5bb3\u4fdd\u5065\u54c1\u7684\u751f\u4ea7\u539f\u6750\u6599\u4e3b\u8981\u6709\u4e24\u5927\u6e90\u5934\u3002',
                u'publishedAt': u'2018-07-14T20:50:00Z',
                u'source': {u'id': None, u'name': u'Chinanews.com'},

我的密码

^{pr2}$

Tags: api新闻u54c1u3000u539fu7684u65b9u5065
2条回答

我成功做到了:

# A small part of the first part of the string provided:
text = u'\u8fdd\u89c4 \u539f\u6599\u836f' 
print(text)
# Prints 违规 原料药

bytes_var = text.encode('utf-8')
print(bytes_var)
# Prints b'\xe8\xbf\x9d\xe8\xa7\x84 \xe5\x8e\x9f\xe6\x96\x99\xe8\x8d\xaf'

现在,这到底有什么问题?这可能与版本有关;我在win10下运行python3.6.5。在

您使用的是python2.7,它使用unicode类型来存储Unicode字符串(例如存储在JSON中的字符串)。unicode类型的repr使用unicode转义符(\uXXXX)打印所有非ASCII字符,这就是您在pprint输出中看到的内容。在

您需要单独打印值才能查看字符:

>>> print repr(u'\u8fdd\u89c4 \u539f\u6599\u836f')
u'\u8fdd\u89c4 \u539f\u6599\u836f'
>>> print u'\u8fdd\u89c4 \u539f\u6599\u836f'
违规 原料药

因此,在你的情况下,你可以做一些类似的事情

^{pr2}$

相关问题 更多 >

    热门问题