Reputation: 19
I'm trying to run this example provided from NLTK book here:
>>> from nltk import load_parser
>>> cp = load_parser('grammars/book_grammars/sql0.fcfg')
>>> query = 'What cities are located in China'
>>> trees = list(cp.parse(query.split()))
>>> answer = trees[0].label()['SEM']
>>> answer = [s for s in answer if s]
>>> q = ' '.join(answer)
>>> print(q)
SELECT City FROM city_table WHERE Country="china"
but when I type the first line it gives me this error:
NameError: name 'load_parser' is not defined
I tried looking for similar questions but none have the same issue. How can I fix it?
Upvotes: 1
Views: 2633
Reputation: 122240
There are quite some namespace changes since the book release. load_parser
now resides in nltk.parse.util
and is imported at nltk.parse
.
In the latest version of NLTK, from nltk import load_parser
should work:
>>> import nltk
>>> nltk.__version__
'3.2.3'
>>> from nltk import load_parser
Maybe in some NLTK versions, the namespace might not be correct. Or maybe somehow you've polluted your namespace earlier on. If a NameError
occurs, then import the function from where the actual function is located:
from nltk.parse import load_parser
E.g.
>>> from nltk.parse import load_parser
>>> cp = load_parser('grammars/book_grammars/sql0.fcfg')
>>> query = 'What cities are located in China'
>>> trees = list(cp.parse(query.split()))
>>> answer = trees[0].label()['SEM']
>>> answer = [s for s in answer if s]
>>> q = ' '.join(answer)
>>> print q
SELECT City FROM city_table WHERE Country="china"
Upvotes: 1