B
    P?[	                 @   sb   d dl mZ d dlZd dlZd dlmZ dddZdd Zdd	 Zd
Z	dddZ
edkr^e
  dS )    )print_functionN)Nonterminalc             C   s<   |s|   }|dkrtj}t| |g|}|r8t||}|S )am  
    Generates an iterator of all sentences from a CFG.

    :param grammar: The Grammar used to generate sentences.
    :param start: The Nonterminal from which to start generate sentences.
    :param depth: The maximal depth of the generated tree.
    :param n: The maximum number of sentences to return.
    :return: An iterator of lists of terminal tokens.
    N)startsysmaxsize_generate_all	itertoolsislice)grammarr   depthniter r   2lib/python3.7/site-packages/nltk/parse/generate.pygenerate   s    
r   c          
   c   s   |ryFx@t | |d |D ],}x&t| |dd  |D ]}|| V  q2W qW W q tk
r } z|jdkrptdn W d d }~X Y qX ng V  d S )Nr      z maximum recursion depth exceededz7The grammar has rule(s) that yield infinite recursion!!)_generate_oner   RuntimeErrormessage)r
   itemsr   Zfrag1Zfrag2Z_errorr   r   r   r   (   s    
r   c             c   sZ   |dkrVt |trNxB| j|dD ](}x"t| | |d D ]
}|V  q:W q W n|gV  d S )Nr   )Zlhsr   )
isinstancer   Zproductionsr   Zrhs)r
   itemr   ZprodZfragr   r   r   r   :   s    
r   z
  S -> NP VP
  NP -> Det N
  PP -> P NP
  VP -> 'slept' | 'saw' NP | 'walked' PP
  Det -> 'the' | 'a'
  N -> 'man' | 'park' | 'dog'
  P -> 'in' | 'with'
   c             C   sf   ddl m} td| f  tt |t}x4tt|| ddD ]\}}td|d|f  q@W d S )Nr   )CFGz3Generating the first %d sentences for demo grammar:)r   r   z%3d. %s )nltk.grammarr   printdemo_grammarZ
fromstring	enumerater   join)Nr   r
   r   Zsentr   r   r   demoO   s    
r!   __main__)NNN)r   )Z
__future__r   r   r   r   r   r   r   r   r   r!   __name__r   r   r   r   <module>
   s   


