-
Notifications
You must be signed in to change notification settings - Fork 3
/
alphabet.py
48 lines (39 loc) · 895 Bytes
/
alphabet.py
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
class Alphabet(dict):
def __init__(self, start_feature_id=1):
self.fid = start_feature_id
def add(self, item):
idx = self.get(item, None)
if idx is None:
idx = self.fid
self[item] = idx
# self[idx] = item
self.fid += 1
return idx
def dump(self, fname):
with open(fname, "w") as out:
for k in sorted(self.keys()):
out.write("{}\t{}\n".format(k, self[k]))
def test():
import pickle
a = Alphabet()
print a.fid
a.add('2')
a.add('1')
a.add('1')
a.add('10')
print a.fid, a
# for i in range(a.fid):
# print a[i]
for item in a.keys():
print item
# pickle.dump(a, open('/tmp/tmp.pickle', 'w'))
# del a
# a = pickle.load(open('/tmp/tmp.pickle'))
# print a.fid, a
# a.add('4')
# print a.fid, a
# a = Alphabet(start_feature_id=0)
# a.add('4')
# print a
if __name__ == '__main__':
test()