1

我正在尝试在这里运行 NLTK 书中提供的这个示例:

>>> 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"

但是当我输入第一行时,它给了我这个错误:

NameError: name 'load_parser' is not defined

我尝试寻找类似的问题,但没有一个有相同的问题。我该如何解决?

4

2 回答 2

1

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"
于 2017-05-20T15:31:26.357 回答
0

我删除了所有 nltk_data 文件并再次下载它们并且它有效。

于 2017-05-21T17:03:24.623 回答