Python, NLTK: NameError: name 'load_parser' is not defined

2.6k Views Asked by At

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?

2

There are 2 best solutions below

0
On

I removed all nltk_data files and downloaded them again and it worked.

1
On

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"