-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.py
More file actions
executable file
·68 lines (58 loc) · 1.87 KB
/
parse.py
File metadata and controls
executable file
·68 lines (58 loc) · 1.87 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
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env python2
#from pyparsing import Forward, nestedExpr, Word, alphanums
import tree_parser
from math import log
def get_p(t, f):
ft = f[t[0]]
if t[0] in f:
return ft[t[1:]] / float(sum(ft.values()))
else:
return 0.0
def get_logp(t, f):
return log(get_p(t, f))
def traverse(o):
try:
if isinstance(o[1], basestring):
yield (o[0], o[1]) # Terminal
else:
if len(o) > 2: # Non-terminal
yield (o[0], o[1][0], o[2][0])
else:
yield (o[0], o[1][0])
for value in o[1:]:
for subvalue in traverse(value):
yield subvalue
except IndexError:
yield ()
def traverse_parent(parent, o):
"""Append parent tag to child for better context awareness.
"""
try:
if isinstance(o[1], basestring):
yield (parent + '/' + o[0], o[1]) # Terminal
else:
if len(o) > 2: # Non-terminal
yield (parent + '/' + o[0], o[0] + '/' + o[1][0], o[0] + '/' + o[2][0])
else:
yield (parent + '/' + o[0], o[0] + '/' + o[1][0])
for value in o[1:]:
for subvalue in traverse_parent(o[0], value):
yield subvalue
except IndexError:
yield ()
def main():
f = open('data/train_trees')
frequencies = dict()
for i, line in enumerate(f):
l = tree_parser.get_tree(line) # charity from Patrick de Kok
for t in traverse_parent('TOP', l[1]): # skip TOP
if t[0] in frequencies:
if t[1:] in frequencies[t[0]]:
frequencies[t[0]][t[1:]] += 1
else:
frequencies[t[0]][t[1:]] = 1
else:
frequencies[t[0]] = {t[1:]: 1}
print frequencies
if __name__ == '__main__':
main()