How can I convert JSON-encoded data that contains Unicode surrogate pairs to string?(如何将包含Unicode代理项对的JSON编码数据转换为字符串?)
本文介绍了如何将包含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编码数据转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何将包含Unicode代理项对的JSON编码数据转换为字符串?


基础教程推荐
猜你喜欢
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01