-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgamesfile.py
More file actions
58 lines (51 loc) · 1.34 KB
/
Copy pathgamesfile.py
File metadata and controls
58 lines (51 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import re
import bz2
import chess.pgn
moveRegex = re.compile(r'\d+[.][ \.](\S+) (?:{[^}]*} )?(\S+)')
class GamesFile(object):
def __init__(self, path):
if path.endswith('bz2'):
self.f = bz2.open(path, 'rt')
else:
self.f = open(path, 'r')
self.path = path
self.i = 0
def __iter__(self):
try:
while True:
yield next(self)
except StopIteration:
return
def __del__(self):
try:
self.f.close()
except AttributeError:
pass
def __next__(self):
ret = {}
lines = ''
for l in self.f:
self.i += 1
lines += l
if len(l) < 2:
if len(ret) >= 2:
break
else:
raise RuntimeError(l)
else:
try:
k, v, _ = l.split('"')
except ValueError:
#bad line
if l == 'null\n':
pass
else:
raise
else:
ret[k[1:-1]] = v
nl = self.f.readline()
lines += nl
lines += self.f.readline()
if len(lines) < 1:
raise StopIteration
return ret, lines