Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 899
Wolff Avatar asked Dec 02 '22 15:12

Wolff


1 Answers

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']
like image 102
user1611867 Avatar answered Dec 18 '22 14:12

user1611867