-
Notifications
You must be signed in to change notification settings - Fork 0
/
treeutil.py
57 lines (43 loc) · 1.14 KB
/
treeutil.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
from nltk.tree import Tree
import logging
def isterminal(t):
"""
:param t: Subtree
:return: Is this a terminal subtree
"""
return not isinstance(t, Tree)
def ispreterminal(t):
"""
:param t: Subtree
:return: Is this a preterminal subtree
"""
if not isterminal(t):
return all(isterminal(st) for st in t)
else:
return False
def filterLexical(t):
"""
:param t: Tree to be freed from lexical nodes
"""
if ispreterminal(t):
logging.debug( "Delete tree ", t, len(t))
del t[:]
t.append('')
else:
for i in range(len(t)):
filterLexical(t[i])
def testTreeFilter(tree=None):
"""
:param tree: Sample tree string in bracket notation.
"""
if tree:
t = Tree(tree)
else:
t = Tree(
'((S(NP-SBJ (PRP They))(ADVP-TMP (RB never))(VP (VBD considered)(S (NP-SBJ (PRP themselves) (VP (TO to) (VP (VB be) (NP-PRD (NN anything) (RB else)))))))))')
t2 = t.copy(deep=True)
filterLexical(t2)
from nltk.draw.tree import draw_trees
draw_trees(t, t2)
if __name__ == "__main__":
testTreeFilter()