comparison g_chart_parser.py @ 0:e991d4e60c17 draft

planemo upload commit 0203cb3a0b40d9348674b2b098af805e2986abca-dirty
author stevecassidy
date Wed, 12 Oct 2016 22:17:53 -0400
parents
children fb617586f4b2
comparison
equal deleted inserted replaced
-1:000000000000 0:e991d4e60c17
1 import sys
2 import nltk
3 import argparse
4 from nltk.corpus import PlaintextCorpusReader
5
6 def arguments():
7 parser = argparse.ArgumentParser(description="run NER on a text")
8 parser.add_argument('--input', required=True, action="store", type=str, help="input text file")
9 parser.add_argument('--grammar', required=True, action="store", type=str, help="grammar file")
10 parser.add_argument('--output', required=True, action="store", type=str, help="output file path")
11 args = parser.parse_args()
12 return args
13
14
15 def chart_parse(in_file, grammar_file, out_file):
16 text = unicode(open(in_file, 'r').read(), errors='ignore')
17 output = open(out_file, 'w')
18 grammar_string = unicode(open(grammar_file, 'r').read(), errors='ignore')
19 try:
20 grammar = nltk.parse_cfg(grammar_string)
21 parser = nltk.ChartParser(grammar)
22 sentences = nltk.sent_tokenize(text)
23 for sentence in sentences:
24 words = nltk.word_tokenize(sentence)
25 tree = parser.parse(words)
26 output.write(tree.pprint())
27 output.write('\n')
28 except Exception, e:
29 message = "Error with parsing. Check the input files are correct and the grammar contains every word in the input sequence. \n----\n" + str(e)
30 sys.stderr.write(message)
31 sys.exit()
32 output.close()
33
34 if __name__ == '__main__':
35 args = arguments()
36 chart_parse(args.input, args.grammar, args.output)
37
38