Stanford Parser and NLTK windows

2020-08-02 11:39发布

问题:

I am trying to run Stanford Parser in NLTK in Windows. I am doing it in python. My code for the same is

import os

from nltk.parse import stanford
os.environ['JAVAHOME'] = 'C:/Program Files/Java/jdk1.8.0_25/bin'
os.environ['STANFORD_PARSER'] = 'C:/jars'
os.environ['STANFORD_MODELS'] = 'C:/jars'

parser =stanford.StanfordParser(model_path="C:/Users/pc/Desktop/Project/englishPCFG.ser.gz")
sentences = parser.raw_parse_sents(("Hello, My name is Melroy.", "What is your name?"))


for i in sentences:
    print i

This is the output it gave

listiterator object at 0x03FB6150  
listiterator object at 0x03FB61B0

I am looking for the following output:

Tree('ROOT', [Tree('S', [Tree('INTJ', [Tree('UH', ['Hello'])]), Tree(',',          [',']), Tree('NP', [Tree('PRP$', ['My']), Tree('NN', ['name'])]), Tree('VP', [Tree('VBZ', ['is']), Tree('ADJP', [Tree('JJ', ['Melroy'])])]), Tree('.', ['.'])])]), Tree('ROOT', [Tree('SBARQ', [Tree('WHNP', [Tree('WP', ['What'])]), Tree('SQ', [Tree('VBZ', ['is']), Tree('NP', [Tree('PRP$', ['your']), Tree('NN', ['name'])])]), Tree('.', ['?'])])])]

回答1:

raw_parse_sents returns a list of listiterators. You can iterate through them like this:

for myListiterator in sentences:
    for t in myListiterator:
        print t

> (ROOT
>   (S
>     (INTJ (UH Hello))
>     (, ,)
>     (NP (PRP$ My) (NN name))
>     (VP (VBZ is) (ADJP (JJ Melroy)))
>     (. .)))
> (ROOT
>   (SBARQ
>     (WHNP (WP What))
>     (SQ (VBZ is) (NP (PRP$ your) (NN name)))
>     (. ?)))

If you want the exact output format you quoted, you can do it like this:

print [list(i)[0] for i in sentences]

> [Tree('ROOT', [Tree('S', [Tree('INTJ', [Tree('UH', ['Hello'])]), Tree(',', [',']), Tree('NP', [Tree('PRP$', ['My']), Tree('NN', ['name'])]), Tree('VP', [Tree('VBZ', ['is']), Tree('ADJP', [Tree('JJ', ['Melroy'])])]), Tree('.', ['.'])])]), Tree('ROOT', [Tree('SBARQ', [Tree('WHNP', [Tree('WP', ['What'])]), Tree('SQ', [Tree('VBZ', ['is']), Tree('NP', [Tree('PRP$', ['your']), Tree('NN', ['name'])])]), Tree('.', ['?'])])])]