weixin_43884285 2019-03-07 23:27 采纳率: 50%
浏览 5165
已采纳

python处理txt文件,怎么把文本形式的数据处理成字典

如下:

{"item_id": 4036886, "title_features": {"1": 1, "2": 1, "3": 1, "4": 1, "5": 1, "6": 1}}
{"item_id": 2893187, "title_features": {"8": 1, "9": 1, "7": 1}}
{"item_id": 338441, "title_features": {"16": 1, "17": 1, "18": 1, "10": 1, "11": 1, "12": 1, "13": 1, "14": 1, "15": 1}}
{"item_id": 2508763, "title_features": {"72": 1, "73": 1, "74": 1, "75": 1, "71": 1}}
{"item_id": 305495, "title_features": {"80": 1, "76": 1, "77": 1, "78": 1, "79": 1}}
{"item_id": 3096313, "title_features": {"81": 1, "82": 1, "83": 1, "84": 1, "85": 1, "86": 1}}

节选了一段储存在文本文档里的数据,形式是字典的样子,怎么能处理成字典的储存方式呢?
谢谢各位前辈了!

  • 写回答

2条回答

  • 毕小宝 博客专家认证 2019-03-08 10:00
    关注

    曹老师回答的是核心API,我测试了下实现代码:

    import json
    f = open("info.txt")
    line = f.readline()
    while line:
        #dump将字符串转换成字典
        d1=json.loads(line)
        print (type(d1))
        print (d1['item_id'])
        line = f.readline()
    
    f.close()
    

    只用loads就能将字符转成字典了,加上dumps后转成的就是字符类型。
    运行结果:

    <class 'dict'>
    4036886
    <class 'dict'>
    2893187
    <class 'dict'>
    338441
    <class 'dict'>
    2508763
    <class 'dict'>
    305495
    <class 'dict'>
    3096313
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr