simple.doctest 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. .. Copyright (C) 2001-2020 NLTK Project
  2. .. For license information, see LICENSE.TXT
  3. =================
  4. EasyInstall Tests
  5. =================
  6. This file contains some simple tests that will be run by EasyInstall in
  7. order to test the installation when NLTK-Data is absent.
  8. ------------
  9. Tokenization
  10. ------------
  11. >>> from nltk.tokenize import wordpunct_tokenize
  12. >>> s = ("Good muffins cost $3.88\nin New York. Please buy me\n"
  13. ... "two of them.\n\nThanks.")
  14. >>> wordpunct_tokenize(s) # doctest: +NORMALIZE_WHITESPACE
  15. ['Good', 'muffins', 'cost', '$', '3', '.', '88', 'in', 'New', 'York', '.',
  16. 'Please', 'buy', 'me', 'two', 'of', 'them', '.', 'Thanks', '.']
  17. -------
  18. Metrics
  19. -------
  20. >>> from nltk.metrics import precision, recall, f_measure
  21. >>> reference = 'DET NN VB DET JJ NN NN IN DET NN'.split()
  22. >>> test = 'DET VB VB DET NN NN NN IN DET NN'.split()
  23. >>> reference_set = set(reference)
  24. >>> test_set = set(test)
  25. >>> precision(reference_set, test_set)
  26. 1.0
  27. >>> print(recall(reference_set, test_set))
  28. 0.8
  29. >>> print(f_measure(reference_set, test_set))
  30. 0.88888888888...
  31. ------------------
  32. Feature Structures
  33. ------------------
  34. >>> from nltk import FeatStruct
  35. >>> fs1 = FeatStruct(PER=3, NUM='pl', GND='fem')
  36. >>> fs2 = FeatStruct(POS='N', AGR=fs1)
  37. >>> print(fs2)
  38. [ [ GND = 'fem' ] ]
  39. [ AGR = [ NUM = 'pl' ] ]
  40. [ [ PER = 3 ] ]
  41. [ ]
  42. [ POS = 'N' ]
  43. >>> print(fs2['AGR'])
  44. [ GND = 'fem' ]
  45. [ NUM = 'pl' ]
  46. [ PER = 3 ]
  47. >>> print(fs2['AGR']['PER'])
  48. 3
  49. -------
  50. Parsing
  51. -------
  52. >>> from nltk.parse.recursivedescent import RecursiveDescentParser
  53. >>> from nltk.grammar import CFG
  54. >>> grammar = CFG.fromstring("""
  55. ... S -> NP VP
  56. ... PP -> P NP
  57. ... NP -> 'the' N | N PP | 'the' N PP
  58. ... VP -> V NP | V PP | V NP PP
  59. ... N -> 'cat' | 'dog' | 'rug'
  60. ... V -> 'chased'
  61. ... P -> 'on'
  62. ... """)
  63. >>> rd = RecursiveDescentParser(grammar)
  64. >>> sent = 'the cat chased the dog on the rug'.split()
  65. >>> for t in rd.parse(sent):
  66. ... print(t)
  67. (S
  68. (NP the (N cat))
  69. (VP (V chased) (NP the (N dog) (PP (P on) (NP the (N rug))))))
  70. (S
  71. (NP the (N cat))
  72. (VP (V chased) (NP the (N dog)) (PP (P on) (NP the (N rug)))))