generate.doctest 1.6 KB

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