Reputation: 155
I have looked at similiar questions and get this to work in strings, but cannot figure how to do the same on a json file.
I would like to count each activity type on each date in a json file. The below line works perfectly, however I do not know all the time values, therefore I would like to match any time on each date. I have tried using fnmatch
but it does not return any values.
c = Counter(
item['Activity'] for item in json_data
if item['DateTime'] == '18/02/2019 09:14'
)
The code I am using to pattern match is below.
from collections import Counter
import json
import fnmatch
import re
with open('dataset_3.json', 'r') as json_file:
json_data = json.load(json_file) # loads json data
c = Counter(
item['Activity'] for item in json_data
if item['DateTime'] == fnmatch.filter(item, '18/02/2019' + ' *')
)
print(c)
Upvotes: 1
Views: 245
Reputation: 59178
The fnmatch
module is meant for matching filenames using UNIX-style globs. For general purpose pattern matching, regular expressions are usually a better bet.
However, since in this case you're simply matching the start of item['DateTime']
, the str.startswith()
method is the obvious choice:
c = Counter(
item['Activity'] for item in json_data
if item['DateTime'].startswith('18/02/2019 ')
)
Upvotes: 2