简体   繁体   中英

Python, NLTK, can't import “parse_cfg”?

So I'm working through a tutorial involving python and the NLTK.

I'm currently working with context free grammars.

I type the following command and get an error...

>>> from nltk import parse_cfg
Traceback (most recent call last):
 File "(stdin)", line 1, in (module)
ImportError: cannot import name parse_cfg

Does anyone have any idea what could be causing that? Some of the cfg commands work, but not this one.

We updated the API for NLTK 3. Please read the docs

The way to access the old nltk.parse_cfg() is using CFG.fromstring()

Example from http://www.nltk.org/howto/grammar.html :

>>> from nltk import CFG
>>> grammar = CFG.fromstring("""
... S -> NP VP
... PP -> P NP
... NP -> Det N | NP PP
... VP -> V NP | VP PP
... Det -> 'a' | 'the'
... N -> 'dog' | 'cat'
... V -> 'chased' | 'sat'
... P -> 'on' | 'in'
... """)
>>> grammar
<Grammar with 14 productions>
>>> grammar.start()
S
>>> grammar.productions() 
[S -> NP VP, PP -> P NP, NP -> Det N, NP -> NP PP, VP -> V NP, VP -> VP PP,
Det -> 'a', Det -> 'the', N -> 'dog', N -> 'cat', V -> 'chased', V -> 'sat',
P -> 'on', P -> 'in']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM