swdata/island/match.py
2018-03-20 20:35:36 +08:00

108 lines
2.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
一场比赛的数据
"""
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 the 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
def count(self):
"""
return the amount of results
"""
if self.dtype != 'mid':
raise RuntimeError("count query on raw data.")
return len(self.raw_data)
@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)