1 from nltk_lite.parse import GrammarFile
2 from nltk_lite.parse.featurechart import *
3 from nltk_lite import tokenize
4
5 """
6 An interactive interface to the feature-based parser. Run "featuredemo.py -h" for
7 command-line options.
8
9 This interface will read a grammar from a *.cfg file, in the format of
10 test.cfg. It will prompt for a filename for the grammar (unless one is given on
11 the command line) and for a sentence to parse, then display the edges being
12 generated and any resulting parse trees.
13 """
14
15 -def text_parse(grammar, sent, trace=2, drawtrees=False, latex=False):
16 parser = grammar.earley_parser(trace=trace)
17 print parser._grammar
18 tokens = list(tokenize.whitespace(sent))
19 trees = parser.get_parse_list(tokens)
20 if drawtrees:
21 from treeview import TreeView
22 TreeView(trees)
23 else:
24 for tree in trees:
25 if latex: print tree.latex_qtree()
26 else: print tree
27
29 import sys
30 from optparse import OptionParser, OptionGroup
31 usage = """%%prog [options] [grammar_file]
32
33 by Rob Speer
34 Distributed under the GPL. See LICENSE.TXT for information.""" % globals()
35
36 opts = OptionParser(usage=usage)
37 opts.add_option("-b", "--batch",
38 metavar="FILE", dest="batchfile", default=None,
39 help="Batch test: parse all the lines in a file")
40
41 opts.add_option("-v", "--verbose",
42 action="count", dest="verbosity", default=0,
43 help="show more information during parse")
44 opts.add_option("-q", "--quiet",
45 action="count", dest="quietness", default=0,
46 help="show only the generated parses (default in batch mode)")
47 opts.add_option("-l", "--latex",
48 action="store_true", dest="latex",
49 help="output parses as LaTeX trees (using qtree.sty)")
50 opts.add_option("-d", "--drawtrees",
51 action="store_true", dest="drawtrees",
52 help="show parse trees in a GUI window")
53
54 (options, args) = opts.parse_args()
55 trace = 0
56 batch = False
57
58 if options.batchfile is not None:
59 trace = 0
60 batch = True
61 if options.drawtrees:
62 sys.stderr.write("Cannot use --drawtrees and --batch simultaneously.")
63 sys.exit(1)
64 if options.quietness > 0: trace = 0
65 trace += options.verbosity
66
67 if len(args): filename = args[0]
68 else: filename = None
69
70 if filename is None:
71 sys.stderr.write("Load rules from file: ")
72 filename = sys.stdin.readline()[:-1]
73 if filename == '': return
74
75 grammar = GrammarFile.read_file(filename)
76
77 if not batch:
78 sys.stderr.write("Sentence: ")
79 sentence = sys.stdin.readline()[:-1]
80 if sentence == '': return
81 text_parse(grammar, sentence, trace, options.drawtrees, options.latex)
82 else:
83 for line in open(options.batchfile):
84 sentence = line.strip()
85 if sentence == '': continue
86 if sentence[0] == '#': continue
87 print "Sentence: %s" % sentence
88 text_parse(grammar, sentence, trace, False, options.latex)
89
90 if __name__ == '__main__':
91 main()
92