我有一个巨大的 .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使用json读取一个带表情的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29000494/