99 lines
2.7 KiB
Python
99 lines
2.7 KiB
Python
"""
|
||
一场比赛的数据
|
||
"""
|
||
import json
|
||
|
||
class Match:
|
||
"""Match"""
|
||
|
||
def __init__(self, raw, dtype='json'):
|
||
"""
|
||
:param json_string: string represents data in json format
|
||
"""
|
||
if dtype == 'json':
|
||
self.raw_data = json.loads(raw)
|
||
self.dtype = 'json'
|
||
else:
|
||
self.raw_data = raw
|
||
self.dtype = 'mid'
|
||
|
||
def query(self, cat, act):
|
||
"""
|
||
start a query
|
||
eg. match.query('game', 'created')
|
||
:param cat: category
|
||
"param act: action
|
||
"""
|
||
if self.dtype == 'mid':
|
||
raise RuntimeError("Query on intermediate result.")
|
||
result = []
|
||
for entry in self.raw_data:
|
||
if entry['cat'] == cat and entry['act'] == act:
|
||
result.append(entry)
|
||
return Match(result, dtype='mid')
|
||
|
||
def where(self, where_expr):
|
||
"""
|
||
add some condition
|
||
eg. match.query('player', 'join').where(lambda i: i['pid']==9527)
|
||
"""
|
||
if self.dtype != 'mid':
|
||
raise RuntimeError("Where query on raw data.")
|
||
return Match([item for item in self.raw_data if where_expr(item)], dtype='mid')
|
||
|
||
def orderby(self, key):
|
||
"""
|
||
sort it!
|
||
eg. match.query('player', 'join').where(lambda i: i['pid']<9527).orderby('created_at')
|
||
"""
|
||
if self.dtype != 'mid':
|
||
raise RuntimeError("Orderby query on raw data.")
|
||
|
||
return Match(sorted(self.raw_data, key=lambda x: x[key]), dtype='mid')
|
||
|
||
def select(self, key1, *args):
|
||
"""
|
||
select some columns
|
||
eg. match.query('player', 'join')
|
||
.select('pid', 'created_at')
|
||
.where(lambda i: i['pid']<9527)
|
||
.orderby('created_at')
|
||
"""
|
||
if self.dtype != 'mid':
|
||
raise RuntimeError("select query on raw data.")
|
||
|
||
result = []
|
||
|
||
keys = [key1]
|
||
for k in args:
|
||
keys.append(k)
|
||
|
||
for entry in self.raw_data:
|
||
dct = dict.fromkeys(keys)
|
||
for k in keys:
|
||
dct[k] = entry[k]
|
||
result.append(dct)
|
||
|
||
return Match(result, dtype='mid')
|
||
|
||
def first(self):
|
||
"""
|
||
return first result
|
||
"""
|
||
if self.dtype != 'mid':
|
||
raise RuntimeError("first query on raw data.")
|
||
|
||
rawl = len(self.raw_data)
|
||
return self.raw_data[0] if rawl > 0 else None
|
||
|
||
@staticmethod
|
||
def read_from_json(json_path):
|
||
"""
|
||
从json_path读取json文件,并返回Match
|
||
:param json_path: path to json file
|
||
"""
|
||
json_string = ''
|
||
with open(json_path, 'r', encoding='utf-8') as file:
|
||
json_string = file.read()
|
||
return Match(json_string)
|