【问题标题】:Decoding special characters bytes with double back slashes用双反斜杠解码特殊字符字节
【发布时间】:2020-06-04 11:59:50
【问题描述】:
x = 'Amazing!! Fantastic coffee and cakes to die for \\xf0\\x9f\\x98\\x80\\xf0\\x9f\\x98\\x80'

y = 'There is a line outside the door for good reason! Everything (and there is plenty) is absolutely excellent. As long as you\\xe2\\x80\\x99re a fan of the best freshly made French baked goods and enjoy an amazing croque monsieur, you\\xe2\\x80\\x99ll be happy here!'

如何解码这些字符串并存储在一个平面文件中,以在 csv 中显示所有表情符号和其他特殊字符而不是字节

【问题讨论】:

    标签: python python-3.x encoding utf-8


    【解决方案1】:

    您似乎有xy 作为str 类型。

    你可以这样做来解码字符串:

    x = 'Amazing!! Fantastic coffee and cakes to die for \xf0\x9f\x98\x80\xf0\x9f\x98\x80'
    y = 'There is a line outside the door for good reason! Everything (and there is plenty) is absolutely excellent. As long as you\xe2\x80\x99re a fan of the best freshly made French baked goods and enjoy an amazing croque monsieur, you\xe2\x80\x99ll be happy here!'
    
    print(bytearray([ord(c) for c in x]).decode('utf-8'))
    print(bytearray([ord(c) for c in y]).decode('utf-8'))
    

    打印:

    Amazing!! Fantastic coffee and cakes to die for ??
    There is a line outside the door for good reason! Everything (and there is plenty) is absolutely excellent. As long as you’re a fan of the best freshly made French baked goods and enjoy an amazing croque monsieur, you’ll be happy here!
    

    编辑:如果您的字符串带有双反斜杠,您可以使用ast.literal_eval 对其进行解码:

    x = 'Amazing!! Fantastic coffee and cakes to die for \\xf0\\x9f\\x98\\x80\\xf0\\x9f\\x98\\x80'
    y = 'There is a line outside the door for good reason! Everything (and there is plenty) is absolutely excellent. As long as you\\xe2\\x80\\x99re a fan of the best freshly made French baked goods and enjoy an amazing croque monsieur, you\\xe2\\x80\\x99ll be happy here!'
    
    from ast import literal_eval
    
    print(literal_eval('b"""' + x + '"""').decode('utf-8'))
    print(literal_eval('b"""' + y + '"""').decode('utf-8'))
    

    【讨论】:

    • 我刚刚在 OP 中添加了格式。原文有双反斜杠(但没有代码格式,所以显示为单反斜杠)
    • z = "空间很棒:开放和时尚。服务不是很多。孩子们提供了太多的东西 xf0x9fx99x84。我点了一个灌木,它装在一个高球杯中,一个圆柱形的冰块占了玻璃杯的 90%。三小口长生不老药和一个 9 美元的冰块 xf0x9fx98x86。午餐很美味,但我曾期待并希望在这里能吃到更多。处理此类案件很热门?
    • 工作就像一个魅力。谢谢@h4z3
    猜你喜欢
    • 2021-09-02
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多