我有一个巨大的.json文件
我在读它

json_data=open('file.json')
data = json.load(json_data)


for item in data['payload']['actions']:
    print item['author']
    print item['action_id']
    print item['body']
json_data.close()

最终,其中一个item['body']包含此字符串(实际上是facebook表情符号):
words words stuff stuff\ud83c\udf89\ud83c\udf8a\ud83c\udf87\ud83c\udf86\ud83c\udf08\ud83d\udca5\u2728\ud83d\udcab\ud83d\udc45\ud83d\udeb9\ud83d\udeba\ud83d\udc83\ud83d\ude4c\ud83c\udfc3\ud83d\udc6c
这就导致了这个错误:
Traceback (most recent call last):
  File "curse.py", line 15, in <module>
    print item['body']
  File "C:\python27\lib\encodings\cp437.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 35-63: character maps to <undefined>

有没有办法让它忽略这些?

最佳答案

您可以使用string.printable

import string

try:
    print item['body']
except UnicodeEncodeError:
    print(''.join(c for c in item['body'] if c in string.printable))

关于python - Python使用json读取带有表情符号的字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29000494/

10-11 10:48