[英]How to count occurrences of specific JSON value in python?
I wrote a python script to count number of occurrences of a specific word in JSON but it doesn't count.我写了一个 python 脚本来计算 JSON 中特定单词的出现次数,但它不计算在内。 Here is my JSON file:
这是我的 JSON 文件:
[
{
"status": "passed",
"name": "Whiskers",
"species" : "cat",
"foods": {
"likes": ["celery", "strawberries"],
"dislikes": ["carrots"]
}
},
{
"status": "failed",
"name": "Woof",
"species" : "dog",
"foods": {
"likes": ["dog food"],
"dislikes": ["cat food"]
}
},
{
"status": "failed",
"name": "Fluffy",
"species" : "cat",
"foods": {
"likes": ["canned food"],
"dislikes": ["dry food"]
}
}
]
Here is my python script:这是我的python脚本:
import fileinput
import sys
import webbrowser
import json
from collections import Counter
f = open('simplejson2.json')
data = json.load(f)
c = Counter(k[:] for d in data for k, v in d.items() if k.startswith('sta') and v)
print(json.dumps(c))
for item in data:
if str(item['status']) != 'passed':
c = Counter(k[:] for d in data for k, v in d.items() if k.endswith('led') and v)
print(json.dumps(c))
else:
print('test case passed sucessfully')
I want to find how many times the "failed" word was used in this JSON script.我想找出在这个 JSON 脚本中使用“失败”这个词的次数。
Try this one:试试这个:
import json
f = open('simplejson2.json')
data = json.load(f)
total_len = len(data)
n = 0
count = 0
while n < total_len:
if data[n]["status"] == "failed":
count += 1
if n == total_len-1:
break
n += 1
print("No of failed : %s" % count)
You are unnecessarily making easy things complex in your code.您在代码中不必要地使简单的事情变得复杂。
Your JSON string is a list
of dicts, you could easily iterate over each dict
and count.您的 JSON 字符串是一个字典
list
,您可以轻松地遍历每个dict
和计数。
This code will give you the No. of entries where status
is failed
.此代码将为您提供
status
failed
的条目数。
import json
s = '''[
{
"status": "passed",
"name": "Whiskers",
"species" : "cat",
"foods": {
"likes": ["celery", "strawberries"],
"dislikes": ["carrots"]
}
},
{
"status": "failed",
"name": "Woof",
"species" : "dog",
"foods": {
"likes": ["dog food"],
"dislikes": ["cat food"]
}
},
{
"status": "failed",
"name": "Fluffy",
"species" : "cat",
"foods": {
"likes": ["canned food"],
"dislikes": ["dry food"]
}
}
]'''
d = json.loads(s)
count = 0
for i in d:
if i['status'] == 'failed':
count += 1
print(f'Failed: {count}')
Output:
2
There are an easy way is : Using regular expression.有一个简单的方法是:使用正则表达式。
json_string
is your string. json_string
是你的字符串。
import re
regex = r"failed"
matches = re.findall(regex, json_string, re.MULTILINE)
print(len(matches))
import json
from collections import Counter
data = [
{
"status": "passed",
"name": "Whiskers",
"species" : "cat",
"foods": {
"likes": ["celery", "strawberries"],
"dislikes": ["carrots"]
}
},
{
"status": "failed",
"name": "Woof",
"species" : "dog",
"foods": {
"likes": ["dog food"],
"dislikes": ["cat food"]
}
},
{
"status": "failed",
"name": "Fluffy",
"species" : "cat",
"foods": {
"likes": ["canned food"],
"dislikes": ["dry food"]
}
}
]
c = Counter(v[:] for d in data for k, v in d.items() if v=="failed")
print(json.dumps(c))
the output:
{"failed": 2}
Here is the working code for python3.这是python3的工作代码。 You can do this from the dictionary comprehension step itself.
您可以从字典理解步骤本身执行此操作。 No need for further code.
不需要进一步的代码。
import json
from collections import Counter
with open('simplejson2.json', 'r') as f:
str1=f.read()
data=json.loads(str1)
c = Counter(k[:] for d in data for k, v in d.items() if k.startswith('status') and v.startswith('failed'))
#c now has the count. Below it will check if count is 0 or not and print.
if c['status']>0:
print("There are",c['status'],"failed cases")
else:
print("test case passed sucessfully")
You need to familiarize with list and dictionary comprehension to understand this algorithm better.您需要熟悉列表和字典理解才能更好地理解此算法。
Happy learning.快乐学习。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.