![](/img/trans.png)
[英]In Python (and attrs), can I export a field to yaml using a different name?
[英]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.