1.. Copyright (C) 2001-2019 NLTK Project 2.. For license information, see LICENSE.TXT 3 4=============================================== 5Generating sentences from context-free grammars 6=============================================== 7 8An example grammar: 9 10 >>> from nltk.parse.generate import generate, demo_grammar 11 >>> from nltk import CFG 12 >>> grammar = CFG.fromstring(demo_grammar) 13 >>> print(grammar) 14 Grammar with 13 productions (start state = S) 15 S -> NP VP 16 NP -> Det N 17 PP -> P NP 18 VP -> 'slept' 19 VP -> 'saw' NP 20 VP -> 'walked' PP 21 Det -> 'the' 22 Det -> 'a' 23 N -> 'man' 24 N -> 'park' 25 N -> 'dog' 26 P -> 'in' 27 P -> 'with' 28 29The first 10 generated sentences: 30 31 >>> for sentence in generate(grammar, n=10): 32 ... print(' '.join(sentence)) 33 the man slept 34 the man saw the man 35 the man saw the park 36 the man saw the dog 37 the man saw a man 38 the man saw a park 39 the man saw a dog 40 the man walked in the man 41 the man walked in the park 42 the man walked in the dog 43 44All sentences of max depth 4: 45 46 >>> for sentence in generate(grammar, depth=4): 47 ... print(' '.join(sentence)) 48 the man slept 49 the park slept 50 the dog slept 51 a man slept 52 a park slept 53 a dog slept 54 55The number of sentences of different max depths: 56 57 >>> len(list(generate(grammar, depth=3))) 58 0 59 >>> len(list(generate(grammar, depth=4))) 60 6 61 >>> len(list(generate(grammar, depth=5))) 62 42 63 >>> len(list(generate(grammar, depth=6))) 64 114 65 >>> len(list(generate(grammar))) 66 114 67 68