projectivedependencyparser.py 27 KB

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