util.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. # Natural Language Toolkit: Parser Utility Functions
  2. #
  3. # Author: Ewan Klein <ewan@inf.ed.ac.uk>
  4. #
  5. # Copyright (C) 2001-2020 NLTK Project
  6. # URL: <http://nltk.org/>
  7. # For license information, see LICENSE.TXT
  8. """
  9. Utility functions for parsers.
  10. """
  11. from nltk.grammar import CFG, FeatureGrammar, PCFG
  12. from nltk.data import load
  13. from nltk.parse.chart import Chart, ChartParser
  14. from nltk.parse.pchart import InsideChartParser
  15. from nltk.parse.featurechart import FeatureChart, FeatureChartParser
  16. def load_parser(
  17. grammar_url, trace=0, parser=None, chart_class=None, beam_size=0, **load_args
  18. ):
  19. """
  20. Load a grammar from a file, and build a parser based on that grammar.
  21. The parser depends on the grammar format, and might also depend
  22. on properties of the grammar itself.
  23. The following grammar formats are currently supported:
  24. - ``'cfg'`` (CFGs: ``CFG``)
  25. - ``'pcfg'`` (probabilistic CFGs: ``PCFG``)
  26. - ``'fcfg'`` (feature-based CFGs: ``FeatureGrammar``)
  27. :type grammar_url: str
  28. :param grammar_url: A URL specifying where the grammar is located.
  29. The default protocol is ``"nltk:"``, which searches for the file
  30. in the the NLTK data package.
  31. :type trace: int
  32. :param trace: The level of tracing that should be used when
  33. parsing a text. ``0`` will generate no tracing output;
  34. and higher numbers will produce more verbose tracing output.
  35. :param parser: The class used for parsing; should be ``ChartParser``
  36. or a subclass.
  37. If None, the class depends on the grammar format.
  38. :param chart_class: The class used for storing the chart;
  39. should be ``Chart`` or a subclass.
  40. Only used for CFGs and feature CFGs.
  41. If None, the chart class depends on the grammar format.
  42. :type beam_size: int
  43. :param beam_size: The maximum length for the parser's edge queue.
  44. Only used for probabilistic CFGs.
  45. :param load_args: Keyword parameters used when loading the grammar.
  46. See ``data.load`` for more information.
  47. """
  48. grammar = load(grammar_url, **load_args)
  49. if not isinstance(grammar, CFG):
  50. raise ValueError("The grammar must be a CFG, " "or a subclass thereof.")
  51. if isinstance(grammar, PCFG):
  52. if parser is None:
  53. parser = InsideChartParser
  54. return parser(grammar, trace=trace, beam_size=beam_size)
  55. elif isinstance(grammar, FeatureGrammar):
  56. if parser is None:
  57. parser = FeatureChartParser
  58. if chart_class is None:
  59. chart_class = FeatureChart
  60. return parser(grammar, trace=trace, chart_class=chart_class)
  61. else: # Plain CFG.
  62. if parser is None:
  63. parser = ChartParser
  64. if chart_class is None:
  65. chart_class = Chart
  66. return parser(grammar, trace=trace, chart_class=chart_class)
  67. def taggedsent_to_conll(sentence):
  68. """
  69. A module to convert a single POS tagged sentence into CONLL format.
  70. >>> from nltk import word_tokenize, pos_tag
  71. >>> text = "This is a foobar sentence."
  72. >>> for line in taggedsent_to_conll(pos_tag(word_tokenize(text))):
  73. ... print(line, end="")
  74. 1 This _ DT DT _ 0 a _ _
  75. 2 is _ VBZ VBZ _ 0 a _ _
  76. 3 a _ DT DT _ 0 a _ _
  77. 4 foobar _ JJ JJ _ 0 a _ _
  78. 5 sentence _ NN NN _ 0 a _ _
  79. 6 . _ . . _ 0 a _ _
  80. :param sentence: A single input sentence to parse
  81. :type sentence: list(tuple(str, str))
  82. :rtype: iter(str)
  83. :return: a generator yielding a single sentence in CONLL format.
  84. """
  85. for (i, (word, tag)) in enumerate(sentence, start=1):
  86. input_str = [str(i), word, "_", tag, tag, "_", "0", "a", "_", "_"]
  87. input_str = "\t".join(input_str) + "\n"
  88. yield input_str
  89. def taggedsents_to_conll(sentences):
  90. """
  91. A module to convert the a POS tagged document stream
  92. (i.e. list of list of tuples, a list of sentences) and yield lines
  93. in CONLL format. This module yields one line per word and two newlines
  94. for end of sentence.
  95. >>> from nltk import word_tokenize, sent_tokenize, pos_tag
  96. >>> text = "This is a foobar sentence. Is that right?"
  97. >>> sentences = [pos_tag(word_tokenize(sent)) for sent in sent_tokenize(text)]
  98. >>> for line in taggedsents_to_conll(sentences):
  99. ... if line:
  100. ... print(line, end="")
  101. 1 This _ DT DT _ 0 a _ _
  102. 2 is _ VBZ VBZ _ 0 a _ _
  103. 3 a _ DT DT _ 0 a _ _
  104. 4 foobar _ JJ JJ _ 0 a _ _
  105. 5 sentence _ NN NN _ 0 a _ _
  106. 6 . _ . . _ 0 a _ _
  107. <BLANKLINE>
  108. <BLANKLINE>
  109. 1 Is _ VBZ VBZ _ 0 a _ _
  110. 2 that _ IN IN _ 0 a _ _
  111. 3 right _ NN NN _ 0 a _ _
  112. 4 ? _ . . _ 0 a _ _
  113. <BLANKLINE>
  114. <BLANKLINE>
  115. :param sentences: Input sentences to parse
  116. :type sentence: list(list(tuple(str, str)))
  117. :rtype: iter(str)
  118. :return: a generator yielding sentences in CONLL format.
  119. """
  120. for sentence in sentences:
  121. for input_str in taggedsent_to_conll(sentence):
  122. yield input_str
  123. yield "\n\n"
  124. ######################################################################
  125. # { Test Suites
  126. ######################################################################
  127. class TestGrammar(object):
  128. """
  129. Unit tests for CFG.
  130. """
  131. def __init__(self, grammar, suite, accept=None, reject=None):
  132. self.test_grammar = grammar
  133. self.cp = load_parser(grammar, trace=0)
  134. self.suite = suite
  135. self._accept = accept
  136. self._reject = reject
  137. def run(self, show_trees=False):
  138. """
  139. Sentences in the test suite are divided into two classes:
  140. - grammatical (``accept``) and
  141. - ungrammatical (``reject``).
  142. If a sentence should parse accordng to the grammar, the value of
  143. ``trees`` will be a non-empty list. If a sentence should be rejected
  144. according to the grammar, then the value of ``trees`` will be None.
  145. """
  146. for test in self.suite:
  147. print(test["doc"] + ":", end=" ")
  148. for key in ["accept", "reject"]:
  149. for sent in test[key]:
  150. tokens = sent.split()
  151. trees = list(self.cp.parse(tokens))
  152. if show_trees and trees:
  153. print()
  154. print(sent)
  155. for tree in trees:
  156. print(tree)
  157. if key == "accept":
  158. if trees == []:
  159. raise ValueError("Sentence '%s' failed to parse'" % sent)
  160. else:
  161. accepted = True
  162. else:
  163. if trees:
  164. raise ValueError("Sentence '%s' received a parse'" % sent)
  165. else:
  166. rejected = True
  167. if accepted and rejected:
  168. print("All tests passed!")
  169. def extract_test_sentences(string, comment_chars="#%;", encoding=None):
  170. """
  171. Parses a string with one test sentence per line.
  172. Lines can optionally begin with:
  173. - a bool, saying if the sentence is grammatical or not, or
  174. - an int, giving the number of parse trees is should have,
  175. The result information is followed by a colon, and then the sentence.
  176. Empty lines and lines beginning with a comment char are ignored.
  177. :return: a list of tuple of sentences and expected results,
  178. where a sentence is a list of str,
  179. and a result is None, or bool, or int
  180. :param comment_chars: ``str`` of possible comment characters.
  181. :param encoding: the encoding of the string, if it is binary
  182. """
  183. if encoding is not None:
  184. string = string.decode(encoding)
  185. sentences = []
  186. for sentence in string.split("\n"):
  187. if sentence == "" or sentence[0] in comment_chars:
  188. continue
  189. split_info = sentence.split(":", 1)
  190. result = None
  191. if len(split_info) == 2:
  192. if split_info[0] in ["True", "true", "False", "false"]:
  193. result = split_info[0] in ["True", "true"]
  194. sentence = split_info[1]
  195. else:
  196. result = int(split_info[0])
  197. sentence = split_info[1]
  198. tokens = sentence.split()
  199. if tokens == []:
  200. continue
  201. sentences += [(tokens, result)]
  202. return sentences
  203. # nose thinks it is a test
  204. extract_test_sentences.__test__ = False