【问题标题】:how to convert unicode character (\u00a3) to human readable string (£) in python如何在python中将unicode字符(\u00a3)转换为人类可读的字符串(£)
【发布时间】:2018-09-26 06:29:06
【问题描述】:

我有一种方法可以接收来自第 3 方的数据,例如

def func(**kwagrs):
    print kwagrs

输出
{'payload': u'{"id":"50b4f4b3e319586b10230f68d21f5edb","data":{"message":"message is \\u00a3 150 \\u2192\\u00c5\\u25024\\u00e9","length": 47}}'}

如何在 python 中将 \\u00a3 转换为 £ 此外,您注意到有效负载的值类型是 Unicode,而不是字典或 JSON
我试图在 StackOverflow 中找到类似的问题,但没有找到任何解决方案。

【问题讨论】:

    标签: python-2.7


    【解决方案1】:

    ValueError: unichr() arg not in range(0x10000) (narrow Python build)的帮助下,我来到了

    import struct
    def unichar(i):
        try:
            return unichr(i)
        except ValueError:
            return struct.pack('i', i).decode('utf-32')
    
    def func(arg):
        msg = args['payload']['data']['message']
        # msg = 'message is \\u00a3 150 \\u2192\\u00c5\\u25024\\u00e9'
        print ' '.join(''.join([unichar(int(ch, 16)) for ch in chunk.split('\\u')[1:]]) if chunk.startswith('\\u') else
        chunk for chunk in msg.split(' '))
    
    func({'payload':{'data':{'message':"message is \\u00a3 150 \\u2192\\u00c5\\u25024\\u00e9"}}})
    

    如果我们运行上面的代码,我们会得到 消息是 £150 →Å?é。 注意:我们可能有更好的解析代码...

    【讨论】:

      猜你喜欢
      • 2016-12-20
      • 2019-05-12
      • 2012-03-31
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-13
      相关资源
      最近更新 更多