【问题标题】:Python using json to read a string with emoticonsPython使用json读取带表情的字符串
【发布时间】:2015-03-12 01:34:05
【问题描述】:

我有一个巨大的.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>

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

【问题讨论】:

  • 你的意思是除了 try/except 块?
  • 我希望它仍然打印字符串的其余部分。在它不会打印的字符之前有单词。我想我应该指定的。

标签: python json facebook emoticons


【解决方案1】:

您可以使用string.printable

import string

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多