繁体   English   中英

我可以使用python“计算”json文件中的字段/名称出现的次数吗? 我不需要字段中的值,但需要名称出现

[英]Can I "count" the number of times a field/name in a json file occurs using python? I do not need the value in the field but the name occurrence

我在一个文本文件中有json,格式如下:

{  
   "_id":"123adfvssw",
   "content_type":"video",
   "content_id":"12345",
   "commenter":{  
      "display_name":"student2",
      "name":"student2",
      "type":"user",
   },
   "source":"chat",
   "state":"published",
   "message":{  
      "body":"the world",
      "fragments":[  
         {  
            "text":"the world"
         }
      ],
      "is_action":false
   },
   "more_replies":false
}
{  
   "_id":"123adfvssw",
   "content_type":"video",
   "content_id":"12345",
   "commenter":{  
      "display_name":"student",
      "name":"student",
      "type":"user",
   },
   "source":"chat",
   "state":"published",
   "message":{  
      "body":"the space",
      "fragments":[  
         {  
            "text":"the space"
         }
      ],
      "is_action":false
   },
   "more_replies":false
}

我想遍历文本文件并计算评论者字段出现的次数,并将结果保存在另一个文本文件中,格式如下:

例如:

文件名评论者 2


我有一些代码,但是在计算字段名称的出现而不是它们的值时遇到了问题。

import json
import  requests
>>> from collections import Counter
>>> filepath="/chatinfo.txt"
>>> with open(filepath) as f:
...     for line in f:
...             jsondata = json.loads(line)
...             dictjson = json.dumps(jsondata)
...             len(jsondata["commenter"])

但是, len 正在计算嵌套在 commenter 字段内的字段数。

任何人都可以给我一个想法,我可以使用什么来计算评论者字段名称的出现次数,并可能在评论者字段不存在时设置异常?

尝试这个

num_with_field = 0
for line in f:
    jsondata = json.loads(line)
    dictjson = json.dumps(jsondata)
    if "commenter" in jsondata:
        num_with_field += 1

in关键字检查给定的字典是否包含给定的键。

编写生成的文件由您决定。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM