2015-05-31
Ongoing-Study/ucps.py at master · myd7349/Ongoing-Study · GitHub
----
2015-06-03
我之前贴的代码具有误导性。因为我的代码实际上是在 raw string literal 和 str 转换。即:
ucps_to_str(r'\u8bf7') # 注意这里是一个 raw string literal,即实际上不是 '\u8bf7' 而是 '\\u8bf7'
->
请
对不起!
如果是 Python 3,我赞同 @竺夏栋 的回答:先看一下 text 的 type。如果是 str,应该是不需要转码(Python documentation:Textual data in Python is handled with str objects, or strings. Strings are immutable sequences of Unicode code points.)。如果是 bytes,则转之。
>>> '\u8bf7'
'请'
>>> b'\u8bf7'
b'\\u8bf7'
>>> b'\u8bf7'.decode('unicode-escape')
'请'
>>> b'\u8bf7'.decode('unicode_escape')
'请'
>>> r'\u8bf7' # 我写的脚本是处理这种情况的
'\\u8bf7'
>>> ucps_to_str(r'\u8bf7')
'请'
>>> '请'.encode('unicode-escape')
b'\\u8bf7'
>>> _.decode('unicode-escape')
'请'
--