4
votes

How can I convert the following Unicode string to Chinese characters?

The string is:

'\\u5982\\u679c\\u6211\\u662f\\u4e00\\u4e2a\\u4ece\\u524d\\u7684\\u54f2\\u4eba\\uff0c\\u6765\\u5230\\u4eca\\u5929\\u7684\\u4e16\\u754c\\uff0c\\u6211\\u4f1a\\u6700\\u6000\\u5ff5\\u4ec0\\u4e48\\uff1f'

And I want it to be:

如果我是一个从前的哲人,来到今天的世界,我会最怀念什么?
1
Did you try looking at what the function is doing? - Ignacio Vazquez-Abrams
line.strip(u'<sentence S=">') is the same as line.strip(u'=<>"censSt '). It'll strip the characters in any order. - Blender
@IgnacioVazquez-Abrams I want to extract the desired sentence from the file through get_str_segmented function. but the extracted sentence was not in chinese but '\u5982\u679c\u6211\u662f\u4e00'. - user2870222
I didn't ask what it was supposed to do, I asked what it was doing. - Ignacio Vazquez-Abrams
@IgnacioVazquez-Abrams it returns unicode? and I want it displayed in chinese, but I don't know what to do. - user2870222

1 Answers

18
votes

Decode it using unicode-escape will give you what you want.

Python 2.7

>>> print '\\u5982\\u679c\\u6211\\u662f\\u4e00\\u4e2a\\u4ece\\u524d\\u7684\\u54f2\\u4eba\\uff0c\\u6765\\u5230\\u4eca\\u5929\\u7684\\u4e16\\u754c\\uff0c\\u6211\\u4f1a\\u6700\\u6000\\u5ff5\\u4ec0\\u4e48\\uff1f'.decode('unicode-escape')
如果我是一个从前的哲人,来到今天的世界,我会最怀念什么?

Python 3.x

>>> print('\\u5982\\u679c\\u6211\\u662f\\u4e00\\u4e2a\\u4ece\\u524d\\u7684\\u54f2\\u4eba\\uff0c\\u6765\\u5230\\u4eca\\u5929\\u7684\\u4e16\\u754c\\uff0c\\u6211\\u4f1a\\u6700\\u6000\\u5ff5\\u4ec0\\u4e48\\uff1f'.encode('ascii').decode('unicode-escape'))
如果我是一个从前的哲人,来到今天的世界,我会最怀念什么?
>>> print(b'\\u5982\\u679c\\u6211\\u662f\\u4e00\\u4e2a\\u4ece\\u524d\\u7684\\u54f2\\u4eba\\uff0c\\u6765\\u5230\\u4eca\\u5929\\u7684\\u4e16\\u754c\\uff0c\\u6211\\u4f1a\\u6700\\u6000\\u5ff5\\u4ec0\\u4e48\\uff1f'.decode('unicode-escape'))
如果我是一个从前的哲人,来到今天的世界,我会最怀念什么?