python 字典格式的文本写入文件,中文乱码(Unicode)的问题

最近在做命名实体识别,需要处理数据,将字典格式的标记文本写入文件
然后一搜发现可以变成json再write到文件里(json.dumps),一试发现中文全部变成Unicode格式,又查如何变成中文。。。发现方法之一 json.load()…发现自己进入一个无限循环

错误的转换方法

import json
dict_1={'val_loss':handle_loss,'val_acc':handle_acc,'val_precision':handle_precision,'val_recall':handle_recall,'val_fmeasure':handle_fmeasure,'val_top_3_categorical_accuracy':handle_top_3_categorical_accuracy}

jsObj = json.dumps(dict_1)

fileObject = open(r'D:\code_python\matrix_dic2.json', 'w')

fileObject.write(jsObj)

fileObject.close()

正确的转换方法例子

使用str(dict)

#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7};
print "Equivalent String : %s" % str (dict)
Equivalent String : {'Age': 7, 'Name': 'Zara'}

2021.01.12更新

应该是使用dump的时候少了一个参数,如果直接用str转换的话,json的双引号都变成了单引号
原因:json.dumps 序列化时默认使用的ascii编码,想输出真正的中文需要指定ensure_ascii=False:更深入分析,是应为dJSON object 不是单纯的unicode实现,而是包含了混合的unicode编码以及已经用utf-8编码之后的字符串。

        def save_data(self,data):
            print(data)
            #ensure_ascii=False
            data=json.dumps(data,ensure_ascii=False)
            print(data)
            with open('ljd.json',mode='w',encoding='utf-8') as f:
                f.write(data)

https://blog.csdn.net/weixin_40612082/article/details/90115045

参考链接

https://www.runoob.com/python/att-dictionary-str.html
https://blog.csdn.net/weixin_42023936/article/details/87604592

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值