如何将包含Unicode代理项对的JSON编码数据转换为字符串? [英] How can I convert JSON-encoded data that contains Unicode surrogate pairs to string?

查看:26
本文介绍了如何将包含Unicode代理项对的JSON编码数据转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试使用Unicode指示器的数据,并将其打印为表情符号。它目前在txt中。文件,但我稍后会写入到EXCEL文件。所以不管怎样,我收到了一个错误,我不确定该如何处理。这是我正在阅读的文本:

"Thanks @UglyGod ud83dude4f https:\/\/t.co\/8zVVNtv1o6"
"RT @Rosssen: Multiculti beatdown ud83dude4f https:\/\/t.co\/fhwVkjhFFC"

以下是我的代码:

sampleFile= open('tweets.txt', 'r').read()
splitFile=sampleFile.split('
')
for line in sampleFile:
    x=line.encode('utf-8')
    print(x.decode('unicode-escape'))

这是错误消息:

UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 0:  at end of string

有什么想法吗? 这就是数据最初的生成方式。

class listener(StreamListener):

    def on_data(self, data):
        # Check for a field unique to tweets (if missing, return immediately)
        if "in_reply_to_status_id" not in data:
            return
        with open("see_no_evil_monkey.csv", 'a') as saveFile:
            try:
                saveFile.write(json.dumps(data) + "
")
            except (BaseException, e):
                print ("failed on data", str(e))
                time.sleep(5)
        return True

    def on_error(self, status):
        print (status)

推荐答案

这就是数据最初的生成方式...saveFile.write(json.dumps(data) + " ")

您应该使用json.loads()而不是.decode('unicode-escape')来阅读JSON文本:

#!/usr/bin/env python3
import json

with open('tweets.txt', encoding='ascii') as file:
    for line in file:
        text = json.loads(line)
        print(text)

这篇关于如何将包含Unicode代理项对的JSON编码数据转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆