简体   繁体   English

如何计算python中特定JSON值的出现次数?

[英]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.您需要熟悉列表和字典理解才能更好地理解此算法。

  1. You don't need all those imports for this code to work: only json and Counter needed.您不需要所有这些导入来使此代码工作:只需要 json 和 Counter。 Also, this can be achieved by far less code as others have answered.此外,正如其他人所回答的那样,这可以通过更少的代码来实现。 I'm just posting this for you to easily find the corrections you need in the same code you have.我只是为您发布此信息,以便在您拥有的相同代码中轻松找到您需要的更正。
  2. f.open is discouraged in this age. f.open 在这个时代是不鼓励的。 Start using with open as it will close the file after need.开始使用 open ,因为它会在需要后关闭文件。
  3. Remember the python mantra: code should be kept as simple as possible.记住 python 的口头禅:代码应该尽可能简单。 And if it is necessary, it can be complex but not complicated.如果有必要,它可以很复杂但并不复杂。

Happy learning.快乐学习。

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

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