projectivedependencyparser.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. # Natural Language Toolkit: Dependency Grammars
  2. #
  3. # Copyright (C) 2001-2020 NLTK Project
  4. # Author: Jason Narad <jason.narad@gmail.com>
  5. #
  6. # URL: <http://nltk.org/>
  7. # For license information, see LICENSE.TXT
  8. #
  9. from collections import defaultdict
  10. from itertools import chain
  11. from functools import total_ordering
  12. from nltk.grammar import (
  13. DependencyProduction,
  14. DependencyGrammar,
  15. ProbabilisticDependencyGrammar,
  16. )
  17. from nltk.parse.dependencygraph import DependencyGraph
  18. from nltk.internals import raise_unorderable_types
  19. #################################################################
  20. # Dependency Span
  21. #################################################################
  22. @total_ordering
  23. class DependencySpan(object):
  24. """
  25. A contiguous span over some part of the input string representing
  26. dependency (head -> modifier) relationships amongst words. An atomic
  27. span corresponds to only one word so it isn't a 'span' in the conventional
  28. sense, as its _start_index = _end_index = _head_index for concatenation
  29. purposes. All other spans are assumed to have arcs between all nodes
  30. within the start and end indexes of the span, and one head index corresponding
  31. to the head word for the entire span. This is the same as the root node if
  32. the dependency structure were depicted as a graph.
  33. """
  34. def __init__(self, start_index, end_index, head_index, arcs, tags):
  35. self._start_index = start_index
  36. self._end_index = end_index
  37. self._head_index = head_index
  38. self._arcs = arcs
  39. self._tags = tags
  40. self._comparison_key = (start_index, end_index, head_index, tuple(arcs))
  41. self._hash = hash(self._comparison_key)
  42. def head_index(self):
  43. """
  44. :return: An value indexing the head of the entire ``DependencySpan``.
  45. :rtype: int
  46. """
  47. return self._head_index
  48. def __repr__(self):
  49. """
  50. :return: A concise string representatino of the ``DependencySpan``.
  51. :rtype: str.
  52. """
  53. return "Span %d-%d; Head Index: %d" % (
  54. self._start_index,
  55. self._end_index,
  56. self._head_index,
  57. )
  58. def __str__(self):
  59. """
  60. :return: A verbose string representation of the ``DependencySpan``.
  61. :rtype: str
  62. """
  63. str = "Span %d-%d; Head Index: %d" % (
  64. self._start_index,
  65. self._end_index,
  66. self._head_index,
  67. )
  68. for i in range(len(self._arcs)):
  69. str += "\n%d <- %d, %s" % (i, self._arcs[i], self._tags[i])
  70. return str
  71. def __eq__(self, other):
  72. return (
  73. type(self) == type(other) and self._comparison_key == other._comparison_key
  74. )
  75. def __ne__(self, other):
  76. return not self == other
  77. def __lt__(self, other):
  78. if not isinstance(other, DependencySpan):
  79. raise_unorderable_types("<", self, other)
  80. return self._comparison_key < other._comparison_key
  81. def __hash__(self):
  82. """
  83. :return: The hash value of this ``DependencySpan``.
  84. """
  85. return self._hash
  86. #################################################################
  87. # Chart Cell
  88. #################################################################
  89. class ChartCell(object):
  90. """
  91. A cell from the parse chart formed when performing the CYK algorithm.
  92. Each cell keeps track of its x and y coordinates (though this will probably
  93. be discarded), and a list of spans serving as the cell's entries.
  94. """
  95. def __init__(self, x, y):
  96. """
  97. :param x: This cell's x coordinate.
  98. :type x: int.
  99. :param y: This cell's y coordinate.
  100. :type y: int.
  101. """
  102. self._x = x
  103. self._y = y
  104. self._entries = set([])
  105. def add(self, span):
  106. """
  107. Appends the given span to the list of spans
  108. representing the chart cell's entries.
  109. :param span: The span to add.
  110. :type span: DependencySpan
  111. """
  112. self._entries.add(span)
  113. def __str__(self):
  114. """
  115. :return: A verbose string representation of this ``ChartCell``.
  116. :rtype: str.
  117. """
  118. return "CC[%d,%d]: %s" % (self._x, self._y, self._entries)
  119. def __repr__(self):
  120. """
  121. :return: A concise string representation of this ``ChartCell``.
  122. :rtype: str.
  123. """
  124. return "%s" % self
  125. #################################################################
  126. # Parsing with Dependency Grammars
  127. #################################################################
  128. class ProjectiveDependencyParser(object):
  129. """
  130. A projective, rule-based, dependency parser. A ProjectiveDependencyParser
  131. is created with a DependencyGrammar, a set of productions specifying
  132. word-to-word dependency relations. The parse() method will then
  133. return the set of all parses, in tree representation, for a given input
  134. sequence of tokens. Each parse must meet the requirements of the both
  135. the grammar and the projectivity constraint which specifies that the
  136. branches of the dependency tree are not allowed to cross. Alternatively,
  137. this can be understood as stating that each parent node and its children
  138. in the parse tree form a continuous substring of the input sequence.
  139. """
  140. def __init__(self, dependency_grammar):
  141. """
  142. Create a new ProjectiveDependencyParser, from a word-to-word
  143. dependency grammar ``DependencyGrammar``.
  144. :param dependency_grammar: A word-to-word relation dependencygrammar.
  145. :type dependency_grammar: DependencyGrammar
  146. """
  147. self._grammar = dependency_grammar
  148. def parse(self, tokens):
  149. """
  150. Performs a projective dependency parse on the list of tokens using
  151. a chart-based, span-concatenation algorithm similar to Eisner (1996).
  152. :param tokens: The list of input tokens.
  153. :type tokens: list(str)
  154. :return: An iterator over parse trees.
  155. :rtype: iter(Tree)
  156. """
  157. self._tokens = list(tokens)
  158. chart = []
  159. for i in range(0, len(self._tokens) + 1):
  160. chart.append([])
  161. for j in range(0, len(self._tokens) + 1):
  162. chart[i].append(ChartCell(i, j))
  163. if i == j + 1:
  164. chart[i][j].add(DependencySpan(i - 1, i, i - 1, [-1], ["null"]))
  165. for i in range(1, len(self._tokens) + 1):
  166. for j in range(i - 2, -1, -1):
  167. for k in range(i - 1, j, -1):
  168. for span1 in chart[k][j]._entries:
  169. for span2 in chart[i][k]._entries:
  170. for newspan in self.concatenate(span1, span2):
  171. chart[i][j].add(newspan)
  172. for parse in chart[len(self._tokens)][0]._entries:
  173. conll_format = ""
  174. # malt_format = ""
  175. for i in range(len(tokens)):
  176. # malt_format += '%s\t%s\t%d\t%s\n' % (tokens[i], 'null', parse._arcs[i] + 1, 'null')
  177. # conll_format += '\t%d\t%s\t%s\t%s\t%s\t%s\t%d\t%s\t%s\t%s\n' % (i+1, tokens[i], tokens[i], 'null', 'null', 'null', parse._arcs[i] + 1, 'null', '-', '-')
  178. # Modify to comply with the new Dependency Graph requirement (at least must have an root elements)
  179. conll_format += "\t%d\t%s\t%s\t%s\t%s\t%s\t%d\t%s\t%s\t%s\n" % (
  180. i + 1,
  181. tokens[i],
  182. tokens[i],
  183. "null",
  184. "null",
  185. "null",
  186. parse._arcs[i] + 1,
  187. "ROOT",
  188. "-",
  189. "-",
  190. )
  191. dg = DependencyGraph(conll_format)
  192. # if self.meets_arity(dg):
  193. yield dg.tree()
  194. def concatenate(self, span1, span2):
  195. """
  196. Concatenates the two spans in whichever way possible. This
  197. includes rightward concatenation (from the leftmost word of the
  198. leftmost span to the rightmost word of the rightmost span) and
  199. leftward concatenation (vice-versa) between adjacent spans. Unlike
  200. Eisner's presentation of span concatenation, these spans do not
  201. share or pivot on a particular word/word-index.
  202. :return: A list of new spans formed through concatenation.
  203. :rtype: list(DependencySpan)
  204. """
  205. spans = []
  206. if span1._start_index == span2._start_index:
  207. print("Error: Mismatched spans - replace this with thrown error")
  208. if span1._start_index > span2._start_index:
  209. temp_span = span1
  210. span1 = span2
  211. span2 = temp_span
  212. # adjacent rightward covered concatenation
  213. new_arcs = span1._arcs + span2._arcs
  214. new_tags = span1._tags + span2._tags
  215. if self._grammar.contains(
  216. self._tokens[span1._head_index], self._tokens[span2._head_index]
  217. ):
  218. # print('Performing rightward cover %d to %d' % (span1._head_index, span2._head_index))
  219. new_arcs[span2._head_index - span1._start_index] = span1._head_index
  220. spans.append(
  221. DependencySpan(
  222. span1._start_index,
  223. span2._end_index,
  224. span1._head_index,
  225. new_arcs,
  226. new_tags,
  227. )
  228. )
  229. # adjacent leftward covered concatenation
  230. new_arcs = span1._arcs + span2._arcs
  231. if self._grammar.contains(
  232. self._tokens[span2._head_index], self._tokens[span1._head_index]
  233. ):
  234. # print('performing leftward cover %d to %d' % (span2._head_index, span1._head_index))
  235. new_arcs[span1._head_index - span1._start_index] = span2._head_index
  236. spans.append(
  237. DependencySpan(
  238. span1._start_index,
  239. span2._end_index,
  240. span2._head_index,
  241. new_arcs,
  242. new_tags,
  243. )
  244. )
  245. return spans
  246. #################################################################
  247. # Parsing with Probabilistic Dependency Grammars
  248. #################################################################
  249. class ProbabilisticProjectiveDependencyParser(object):
  250. """A probabilistic, projective dependency parser.
  251. This parser returns the most probable projective parse derived from the
  252. probabilistic dependency grammar derived from the train() method. The
  253. probabilistic model is an implementation of Eisner's (1996) Model C, which
  254. conditions on head-word, head-tag, child-word, and child-tag. The decoding
  255. uses a bottom-up chart-based span concatenation algorithm that's identical
  256. to the one utilized by the rule-based projective parser.
  257. Usage example
  258. -------------
  259. >>> from nltk.parse.dependencygraph import conll_data2
  260. >>> graphs = [
  261. ... DependencyGraph(entry) for entry in conll_data2.split('\\n\\n') if entry
  262. ... ]
  263. >>> ppdp = ProbabilisticProjectiveDependencyParser()
  264. >>> ppdp.train(graphs)
  265. >>> sent = ['Cathy', 'zag', 'hen', 'wild', 'zwaaien', '.']
  266. >>> list(ppdp.parse(sent))
  267. [Tree('zag', ['Cathy', 'hen', Tree('zwaaien', ['wild', '.'])])]
  268. """
  269. def __init__(self):
  270. """
  271. Create a new probabilistic dependency parser. No additional
  272. operations are necessary.
  273. """
  274. def parse(self, tokens):
  275. """
  276. Parses the list of tokens subject to the projectivity constraint
  277. and the productions in the parser's grammar. This uses a method
  278. similar to the span-concatenation algorithm defined in Eisner (1996).
  279. It returns the most probable parse derived from the parser's
  280. probabilistic dependency grammar.
  281. """
  282. self._tokens = list(tokens)
  283. chart = []
  284. for i in range(0, len(self._tokens) + 1):
  285. chart.append([])
  286. for j in range(0, len(self._tokens) + 1):
  287. chart[i].append(ChartCell(i, j))
  288. if i == j + 1:
  289. if tokens[i - 1] in self._grammar._tags:
  290. for tag in self._grammar._tags[tokens[i - 1]]:
  291. chart[i][j].add(
  292. DependencySpan(i - 1, i, i - 1, [-1], [tag])
  293. )
  294. else:
  295. print(
  296. "No tag found for input token '%s', parse is impossible."
  297. % tokens[i - 1]
  298. )
  299. return []
  300. for i in range(1, len(self._tokens) + 1):
  301. for j in range(i - 2, -1, -1):
  302. for k in range(i - 1, j, -1):
  303. for span1 in chart[k][j]._entries:
  304. for span2 in chart[i][k]._entries:
  305. for newspan in self.concatenate(span1, span2):
  306. chart[i][j].add(newspan)
  307. trees = []
  308. max_parse = None
  309. max_score = 0
  310. for parse in chart[len(self._tokens)][0]._entries:
  311. conll_format = ""
  312. malt_format = ""
  313. for i in range(len(tokens)):
  314. malt_format += "%s\t%s\t%d\t%s\n" % (
  315. tokens[i],
  316. "null",
  317. parse._arcs[i] + 1,
  318. "null",
  319. )
  320. # conll_format += '\t%d\t%s\t%s\t%s\t%s\t%s\t%d\t%s\t%s\t%s\n' % (i+1, tokens[i], tokens[i], parse._tags[i], parse._tags[i], 'null', parse._arcs[i] + 1, 'null', '-', '-')
  321. # Modify to comply with recent change in dependency graph such that there must be a ROOT element.
  322. conll_format += "\t%d\t%s\t%s\t%s\t%s\t%s\t%d\t%s\t%s\t%s\n" % (
  323. i + 1,
  324. tokens[i],
  325. tokens[i],
  326. parse._tags[i],
  327. parse._tags[i],
  328. "null",
  329. parse._arcs[i] + 1,
  330. "ROOT",
  331. "-",
  332. "-",
  333. )
  334. dg = DependencyGraph(conll_format)
  335. score = self.compute_prob(dg)
  336. trees.append((score, dg.tree()))
  337. trees.sort()
  338. return (tree for (score, tree) in trees)
  339. def concatenate(self, span1, span2):
  340. """
  341. Concatenates the two spans in whichever way possible. This
  342. includes rightward concatenation (from the leftmost word of the
  343. leftmost span to the rightmost word of the rightmost span) and
  344. leftward concatenation (vice-versa) between adjacent spans. Unlike
  345. Eisner's presentation of span concatenation, these spans do not
  346. share or pivot on a particular word/word-index.
  347. :return: A list of new spans formed through concatenation.
  348. :rtype: list(DependencySpan)
  349. """
  350. spans = []
  351. if span1._start_index == span2._start_index:
  352. print("Error: Mismatched spans - replace this with thrown error")
  353. if span1._start_index > span2._start_index:
  354. temp_span = span1
  355. span1 = span2
  356. span2 = temp_span
  357. # adjacent rightward covered concatenation
  358. new_arcs = span1._arcs + span2._arcs
  359. new_tags = span1._tags + span2._tags
  360. if self._grammar.contains(
  361. self._tokens[span1._head_index], self._tokens[span2._head_index]
  362. ):
  363. new_arcs[span2._head_index - span1._start_index] = span1._head_index
  364. spans.append(
  365. DependencySpan(
  366. span1._start_index,
  367. span2._end_index,
  368. span1._head_index,
  369. new_arcs,
  370. new_tags,
  371. )
  372. )
  373. # adjacent leftward covered concatenation
  374. new_arcs = span1._arcs + span2._arcs
  375. new_tags = span1._tags + span2._tags
  376. if self._grammar.contains(
  377. self._tokens[span2._head_index], self._tokens[span1._head_index]
  378. ):
  379. new_arcs[span1._head_index - span1._start_index] = span2._head_index
  380. spans.append(
  381. DependencySpan(
  382. span1._start_index,
  383. span2._end_index,
  384. span2._head_index,
  385. new_arcs,
  386. new_tags,
  387. )
  388. )
  389. return spans
  390. def train(self, graphs):
  391. """
  392. Trains a ProbabilisticDependencyGrammar based on the list of input
  393. DependencyGraphs. This model is an implementation of Eisner's (1996)
  394. Model C, which derives its statistics from head-word, head-tag,
  395. child-word, and child-tag relationships.
  396. :param graphs: A list of dependency graphs to train from.
  397. :type: list(DependencyGraph)
  398. """
  399. productions = []
  400. events = defaultdict(int)
  401. tags = {}
  402. for dg in graphs:
  403. for node_index in range(1, len(dg.nodes)):
  404. # children = dg.nodes[node_index]['deps']
  405. children = list(chain(*dg.nodes[node_index]["deps"].values()))
  406. nr_left_children = dg.left_children(node_index)
  407. nr_right_children = dg.right_children(node_index)
  408. nr_children = nr_left_children + nr_right_children
  409. for child_index in range(
  410. 0 - (nr_left_children + 1), nr_right_children + 2
  411. ):
  412. head_word = dg.nodes[node_index]["word"]
  413. head_tag = dg.nodes[node_index]["tag"]
  414. if head_word in tags:
  415. tags[head_word].add(head_tag)
  416. else:
  417. tags[head_word] = set([head_tag])
  418. child = "STOP"
  419. child_tag = "STOP"
  420. prev_word = "START"
  421. prev_tag = "START"
  422. if child_index < 0:
  423. array_index = child_index + nr_left_children
  424. if array_index >= 0:
  425. child = dg.nodes[children[array_index]]["word"]
  426. child_tag = dg.nodes[children[array_index]]["tag"]
  427. if child_index != -1:
  428. prev_word = dg.nodes[children[array_index + 1]]["word"]
  429. prev_tag = dg.nodes[children[array_index + 1]]["tag"]
  430. if child != "STOP":
  431. productions.append(DependencyProduction(head_word, [child]))
  432. head_event = "(head (%s %s) (mods (%s, %s, %s) left))" % (
  433. child,
  434. child_tag,
  435. prev_tag,
  436. head_word,
  437. head_tag,
  438. )
  439. mod_event = "(mods (%s, %s, %s) left))" % (
  440. prev_tag,
  441. head_word,
  442. head_tag,
  443. )
  444. events[head_event] += 1
  445. events[mod_event] += 1
  446. elif child_index > 0:
  447. array_index = child_index + nr_left_children - 1
  448. if array_index < nr_children:
  449. child = dg.nodes[children[array_index]]["word"]
  450. child_tag = dg.nodes[children[array_index]]["tag"]
  451. if child_index != 1:
  452. prev_word = dg.nodes[children[array_index - 1]]["word"]
  453. prev_tag = dg.nodes[children[array_index - 1]]["tag"]
  454. if child != "STOP":
  455. productions.append(DependencyProduction(head_word, [child]))
  456. head_event = "(head (%s %s) (mods (%s, %s, %s) right))" % (
  457. child,
  458. child_tag,
  459. prev_tag,
  460. head_word,
  461. head_tag,
  462. )
  463. mod_event = "(mods (%s, %s, %s) right))" % (
  464. prev_tag,
  465. head_word,
  466. head_tag,
  467. )
  468. events[head_event] += 1
  469. events[mod_event] += 1
  470. self._grammar = ProbabilisticDependencyGrammar(productions, events, tags)
  471. def compute_prob(self, dg):
  472. """
  473. Computes the probability of a dependency graph based
  474. on the parser's probability model (defined by the parser's
  475. statistical dependency grammar).
  476. :param dg: A dependency graph to score.
  477. :type dg: DependencyGraph
  478. :return: The probability of the dependency graph.
  479. :rtype: int
  480. """
  481. prob = 1.0
  482. for node_index in range(1, len(dg.nodes)):
  483. # children = dg.nodes[node_index]['deps']
  484. children = list(chain(*dg.nodes[node_index]["deps"].values()))
  485. nr_left_children = dg.left_children(node_index)
  486. nr_right_children = dg.right_children(node_index)
  487. nr_children = nr_left_children + nr_right_children
  488. for child_index in range(0 - (nr_left_children + 1), nr_right_children + 2):
  489. head_word = dg.nodes[node_index]["word"]
  490. head_tag = dg.nodes[node_index]["tag"]
  491. child = "STOP"
  492. child_tag = "STOP"
  493. prev_word = "START"
  494. prev_tag = "START"
  495. if child_index < 0:
  496. array_index = child_index + nr_left_children
  497. if array_index >= 0:
  498. child = dg.nodes[children[array_index]]["word"]
  499. child_tag = dg.nodes[children[array_index]]["tag"]
  500. if child_index != -1:
  501. prev_word = dg.nodes[children[array_index + 1]]["word"]
  502. prev_tag = dg.nodes[children[array_index + 1]]["tag"]
  503. head_event = "(head (%s %s) (mods (%s, %s, %s) left))" % (
  504. child,
  505. child_tag,
  506. prev_tag,
  507. head_word,
  508. head_tag,
  509. )
  510. mod_event = "(mods (%s, %s, %s) left))" % (
  511. prev_tag,
  512. head_word,
  513. head_tag,
  514. )
  515. h_count = self._grammar._events[head_event]
  516. m_count = self._grammar._events[mod_event]
  517. # If the grammar is not covered
  518. if m_count != 0:
  519. prob *= h_count / m_count
  520. else:
  521. prob = 0.00000001 # Very small number
  522. elif child_index > 0:
  523. array_index = child_index + nr_left_children - 1
  524. if array_index < nr_children:
  525. child = dg.nodes[children[array_index]]["word"]
  526. child_tag = dg.nodes[children[array_index]]["tag"]
  527. if child_index != 1:
  528. prev_word = dg.nodes[children[array_index - 1]]["word"]
  529. prev_tag = dg.nodes[children[array_index - 1]]["tag"]
  530. head_event = "(head (%s %s) (mods (%s, %s, %s) right))" % (
  531. child,
  532. child_tag,
  533. prev_tag,
  534. head_word,
  535. head_tag,
  536. )
  537. mod_event = "(mods (%s, %s, %s) right))" % (
  538. prev_tag,
  539. head_word,
  540. head_tag,
  541. )
  542. h_count = self._grammar._events[head_event]
  543. m_count = self._grammar._events[mod_event]
  544. if m_count != 0:
  545. prob *= h_count / m_count
  546. else:
  547. prob = 0.00000001 # Very small number
  548. return prob
  549. #################################################################
  550. # Demos
  551. #################################################################
  552. def demo():
  553. projective_rule_parse_demo()
  554. # arity_parse_demo()
  555. projective_prob_parse_demo()
  556. def projective_rule_parse_demo():
  557. """
  558. A demonstration showing the creation and use of a
  559. ``DependencyGrammar`` to perform a projective dependency
  560. parse.
  561. """
  562. grammar = DependencyGrammar.fromstring(
  563. """
  564. 'scratch' -> 'cats' | 'walls'
  565. 'walls' -> 'the'
  566. 'cats' -> 'the'
  567. """
  568. )
  569. print(grammar)
  570. pdp = ProjectiveDependencyParser(grammar)
  571. trees = pdp.parse(["the", "cats", "scratch", "the", "walls"])
  572. for tree in trees:
  573. print(tree)
  574. def arity_parse_demo():
  575. """
  576. A demonstration showing the creation of a ``DependencyGrammar``
  577. in which a specific number of modifiers is listed for a given
  578. head. This can further constrain the number of possible parses
  579. created by a ``ProjectiveDependencyParser``.
  580. """
  581. print()
  582. print("A grammar with no arity constraints. Each DependencyProduction")
  583. print("specifies a relationship between one head word and only one")
  584. print("modifier word.")
  585. grammar = DependencyGrammar.fromstring(
  586. """
  587. 'fell' -> 'price' | 'stock'
  588. 'price' -> 'of' | 'the'
  589. 'of' -> 'stock'
  590. 'stock' -> 'the'
  591. """
  592. )
  593. print(grammar)
  594. print()
  595. print("For the sentence 'The price of the stock fell', this grammar")
  596. print("will produce the following three parses:")
  597. pdp = ProjectiveDependencyParser(grammar)
  598. trees = pdp.parse(["the", "price", "of", "the", "stock", "fell"])
  599. for tree in trees:
  600. print(tree)
  601. print()
  602. print("By contrast, the following grammar contains a ")
  603. print("DependencyProduction that specifies a relationship")
  604. print("between a single head word, 'price', and two modifier")
  605. print("words, 'of' and 'the'.")
  606. grammar = DependencyGrammar.fromstring(
  607. """
  608. 'fell' -> 'price' | 'stock'
  609. 'price' -> 'of' 'the'
  610. 'of' -> 'stock'
  611. 'stock' -> 'the'
  612. """
  613. )
  614. print(grammar)
  615. print()
  616. print(
  617. "This constrains the number of possible parses to just one:"
  618. ) # unimplemented, soon to replace
  619. pdp = ProjectiveDependencyParser(grammar)
  620. trees = pdp.parse(["the", "price", "of", "the", "stock", "fell"])
  621. for tree in trees:
  622. print(tree)
  623. def projective_prob_parse_demo():
  624. """
  625. A demo showing the training and use of a projective
  626. dependency parser.
  627. """
  628. from nltk.parse.dependencygraph import conll_data2
  629. graphs = [DependencyGraph(entry) for entry in conll_data2.split("\n\n") if entry]
  630. ppdp = ProbabilisticProjectiveDependencyParser()
  631. print("Training Probabilistic Projective Dependency Parser...")
  632. ppdp.train(graphs)
  633. sent = ["Cathy", "zag", "hen", "wild", "zwaaien", "."]
  634. print("Parsing '", " ".join(sent), "'...")
  635. print("Parse:")
  636. for tree in ppdp.parse(sent):
  637. print(tree)
  638. if __name__ == "__main__":
  639. demo()