# parser.py - parses a given sentence using a given grammar definition

import sys, os

from nltk import load_parser

ROOT = os.path.dirname(os.path.abspath(__file__))

GRAMMAR_URL = "file://%(url)s"

# GRAMMAR_DIR = os.path.join(ROOT, 'grammars')

USAGE = "Usage: %(prog)s grammar-file sentence trace cache"

def get_parser(grammar_file, trace=2, cache=False):
    """ loads a parser from the given grammar """

    file = GRAMMAR_URL % {'url': os.path.join(ROOT, grammar_file)}
    return load_parser(file, trace=trace, cache=cache)

def tokenize(sentence):
    """ breaks down a string into tokens for parsing """

    return sentence.split()

def parse(parser, sentence):
    """ gets the best parse trees for this sentence """

    return parser.nbest_parse(tokenize(sentence))

def main():
    if len(sys.argv) < 3:
        print USAGE % sys.argv[0]

    grammar_file = sys.argv[1]
    sentence = sys.argv[2]

    trace = 0
    cache = False

    if len(sys.argv) > 3:
        trace = int(sys.argv[3])

    if len(sys.argv) > 4 and sys.argv[4] == "True":
        cache = True

    parser = get_parser(grammar_file, trace=trace, cache=cache)
    trees = parse(parser, sentence)

    if len(trees) == 0:
        print "No parse trees found"
        return

    for tree in trees:
        print tree

if __name__ == "__main__":
    main()

@@ -79,16 +79,32 @@
  sys, os
+%0Aimport argparse
 %0A%0Afrom n
@@ -262,69 +262,8 @@
 ')%0A%0A
-USAGE = %22Usage: %25(prog)s grammar-file sentence trace cache%22%0A%0A
 def 
@@ -752,268 +752,349 @@
     
-if len(sys.argv) %3C 3:%0A        print USAGE %25 sys.argv%5B0%5D%0A%0A    grammar_file = sys.argv%5B1%5D%0A    sentence = sys.argv%5B2%5D%0A%0A    trace = 0%0A    cache = False%0A%0A    if len(sys.argv) %3E 3:%0A        trace = int(sys.argv%5B3%5D)%0A%0A    if len(sys.argv) %3E 4 and sys.argv%5B4%5D == %22T
+parser = argparse.ArgumentParser()%0A    parser.add_argument('grammar', %0A        help=%22file in local folder with grammar%22)%0A    parser.add_argument('sentence', help=%22sentence to be parsed%22)%0A    parser.add_argument('-t', '--trace', type=int, %0A        help=%22parser debug trace level%22)%0A    parser.add_argument('-c', '--cache', action=%22store_t
 rue%22
-:
+,
 %0A   
@@ -1102,20 +1102,68 @@
     
-cache = True
+help=%22cache grammar or not%22)%0A%0A    args = parser.parse_args()
 %0A%0A  
@@ -1184,36 +1184,36 @@
 _parser(
+args.
 grammar
-_file
 , trace=
 trace, c
@@ -1196,32 +1196,37 @@
 .grammar, trace=
+args.
 trace, cache=cac
@@ -1218,24 +1218,29 @@
 race, cache=
+args.
 cache)%0A    t
@@ -1252,32 +1252,37 @@
 = parse(parser, 
+args.
 sentence)%0A%0A    i

Make parser more flexible