-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcfg_grammar.py
62 lines (50 loc) · 2.06 KB
/
cfg_grammar.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
# -*- encoding: utf-8 -*-
#
# cfg_grammar.py
# Copyright (C) 2009, Alexander Berman. All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# and the GNU Lesser General Public License along with this program.
# If not, see <http://www.gnu.org/licenses/>.
from ibis import *
from nltk import *
######################################################################
# CFG grammar based on NLTK
######################################################################
class CFG_Grammar(Grammar):
"""CFG parser based on NLTK."""
def loadGrammar(self, grammarFilename):
self.parser = parse.load_parser(grammarFilename, trace=1, cache=False)
def interpret(self, input):
"""Parse an input string into a dialogue move or a set of moves."""
try: return self.parseString(input)
except: pass
try: return eval(input)
except: pass
return set([])
def parseString(self, input):
tokens = input.split()
trees = self.parser.nbest_parse(tokens)
sem = trees[0].node['sem']
return self.sem2move(sem)
def sem2move(self, sem):
try: return Answer(sem['Answer'])
except: pass
try:
ans = sem['Answer']
pred = ans['pred']
ind = ans['ind']
#return Answer(Prop((Pred1(pred, Ind(ind), True))))
return Answer(pred+"("+ind+")")
except: pass
try: return Ask(WhQ(Pred1(sem['Ask'])))
except: pass
return None