簡體   English   中英

如何計算python中特定JSON值的出現次數?

[英]How to count occurrences of specific JSON value in python?

我寫了一個 python 腳本來計算 JSON 中特定單詞的出現次數,但它不計算在內。 這是我的 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"]
    }
  }
]

這是我的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')

我想找出在這個 JSON 腳本中使用“失敗”這個詞的次數。

試試這個:

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) 


您在代碼中不必要地使簡單的事情變得復雜。

您的 JSON 字符串是一個字典list ,您可以輕松地遍歷每個dict和計數。

此代碼將為您提供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

有一個簡單的方法是:使用正則表達式。
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}

這是python3的工作代碼。 您可以從字典理解步驟本身執行此操作。 不需要進一步的代碼。

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")

您需要熟悉列表和字典理解才能更好地理解此算法。

  1. 您不需要所有這些導入來使此代碼工作:只需要 json 和 Counter。 此外,正如其他人所回答的那樣,這可以通過更少的代碼來實現。 我只是為您發布此信息,以便在您擁有的相同代碼中輕松找到您需要的更正。
  2. f.open 在這個時代是不鼓勵的。 開始使用 open ,因為它會在需要后關閉文件。
  3. 記住 python 的口頭禪:代碼應該盡可能簡單。 如果有必要,它可以很復雜但並不復雜。

快樂學習。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM