-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathSenTree.py
76 lines (59 loc) · 2.3 KB
/
SenTree.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from nltk.tree import ParentedTree
import _pickle as cPickle
class SenTree(ParentedTree):
def __init__(self, node, children=None):
super(SenTree,self).__init__(node, children)
def left(self):
return self[0]
def right(self):
return self[1]
def isLeaf(self):
return self.height()==2
def getLeafWord(self):
return self[0]
@staticmethod
def getTrees(file='./trees/small.txt',vocabOutFile=None, vocabIndicesMapFile=None):
if vocabIndicesMapFile is None:
return SenTree.constructVocabAndGetTrees(file, vocabOutFile=vocabOutFile)
else:
return SenTree.getTreesGivenVocab(file, vocabIndicesMapFile)
@staticmethod
def getTreesGivenVocab(file, vocabIndicesMapFile):
trees = []
vocabIndicesMap=cPickle.load(open(vocabIndicesMapFile,'rb'))
with open(file, "r") as f:
for line in f:
tree = SenTree.fromstring(line)
SenTree.mapTreeNodes(tree,vocabIndicesMap)
SenTree.castLabelsToInt(tree)
trees.append(tree)
SenTree.vocabSize=len(vocabIndicesMap)
return trees
@staticmethod
def constructVocabAndGetTrees(file, vocabOutFile=None):
trees = []
vocab = set()
with open(file, "r") as f:
for line in f:
tree = SenTree.fromstring(line)
trees.append(tree)
vocab.update(tree.leaves())
vocabIndicesMap = dict(zip(vocab,range(len(vocab))))
vocabIndicesMap['UNK'] = len(vocab)
if vocabOutFile is not None:
with open(vocabOutFile,'wb') as fp: cPickle.dump(vocabIndicesMap,fp)
for tree in trees:
SenTree.mapTreeNodes(tree,vocabIndicesMap)
SenTree.castLabelsToInt(tree)
SenTree.vocabSize=len(vocabIndicesMap)
return trees
@staticmethod
def mapTreeNodes(tree, vocabIndicesMap):
for leafPos in tree.treepositions('leaves'):
if tree[leafPos] in vocabIndicesMap: tree[leafPos] = vocabIndicesMap[tree[leafPos]]
else: tree[leafPos]= vocabIndicesMap['UNK']
@staticmethod
def castLabelsToInt(tree):
for subtree in tree.subtrees():
subtree.set_label(int(subtree.label()))
#trees = SenTree.getTrees()