You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1775 lines
64 KiB

4 years ago
  1. # -*- coding: utf-8 -*-
  2. # Natural Language Toolkit: Text Trees
  3. #
  4. # Copyright (C) 2001-2019 NLTK Project
  5. # Author: Edward Loper <edloper@gmail.com>
  6. # Steven Bird <stevenbird1@gmail.com>
  7. # Peter Ljunglöf <peter.ljunglof@gu.se>
  8. # Nathan Bodenstab <bodenstab@cslu.ogi.edu> (tree transforms)
  9. # URL: <http://nltk.org/>
  10. # For license information, see LICENSE.TXT
  11. """
  12. Class for representing hierarchical language structures, such as
  13. syntax trees and morphological trees.
  14. """
  15. from __future__ import print_function, unicode_literals
  16. import re
  17. from abc import ABCMeta, abstractmethod
  18. from six import string_types, add_metaclass
  19. from nltk.grammar import Production, Nonterminal
  20. from nltk.probability import ProbabilisticMixIn
  21. from nltk.util import slice_bounds
  22. from nltk.compat import python_2_unicode_compatible, unicode_repr
  23. from nltk.internals import raise_unorderable_types
  24. # TODO: add LabelledTree (can be used for dependency trees)
  25. ######################################################################
  26. ## Trees
  27. ######################################################################
  28. @python_2_unicode_compatible
  29. class Tree(list):
  30. """
  31. A Tree represents a hierarchical grouping of leaves and subtrees.
  32. For example, each constituent in a syntax tree is represented by a single Tree.
  33. A tree's children are encoded as a list of leaves and subtrees,
  34. where a leaf is a basic (non-tree) value; and a subtree is a
  35. nested Tree.
  36. >>> from nltk.tree import Tree
  37. >>> print(Tree(1, [2, Tree(3, [4]), 5]))
  38. (1 2 (3 4) 5)
  39. >>> vp = Tree('VP', [Tree('V', ['saw']),
  40. ... Tree('NP', ['him'])])
  41. >>> s = Tree('S', [Tree('NP', ['I']), vp])
  42. >>> print(s)
  43. (S (NP I) (VP (V saw) (NP him)))
  44. >>> print(s[1])
  45. (VP (V saw) (NP him))
  46. >>> print(s[1,1])
  47. (NP him)
  48. >>> t = Tree.fromstring("(S (NP I) (VP (V saw) (NP him)))")
  49. >>> s == t
  50. True
  51. >>> t[1][1].set_label('X')
  52. >>> t[1][1].label()
  53. 'X'
  54. >>> print(t)
  55. (S (NP I) (VP (V saw) (X him)))
  56. >>> t[0], t[1,1] = t[1,1], t[0]
  57. >>> print(t)
  58. (S (X him) (VP (V saw) (NP I)))
  59. The length of a tree is the number of children it has.
  60. >>> len(t)
  61. 2
  62. The set_label() and label() methods allow individual constituents
  63. to be labeled. For example, syntax trees use this label to specify
  64. phrase tags, such as "NP" and "VP".
  65. Several Tree methods use "tree positions" to specify
  66. children or descendants of a tree. Tree positions are defined as
  67. follows:
  68. - The tree position *i* specifies a Tree's *i*\ th child.
  69. - The tree position ``()`` specifies the Tree itself.
  70. - If *p* is the tree position of descendant *d*, then
  71. *p+i* specifies the *i*\ th child of *d*.
  72. I.e., every tree position is either a single index *i*,
  73. specifying ``tree[i]``; or a sequence *i1, i2, ..., iN*,
  74. specifying ``tree[i1][i2]...[iN]``.
  75. Construct a new tree. This constructor can be called in one
  76. of two ways:
  77. - ``Tree(label, children)`` constructs a new tree with the
  78. specified label and list of children.
  79. - ``Tree.fromstring(s)`` constructs a new tree by parsing the string ``s``.
  80. """
  81. def __init__(self, node, children=None):
  82. if children is None:
  83. raise TypeError(
  84. "%s: Expected a node value and child list " % type(self).__name__
  85. )
  86. elif isinstance(children, string_types):
  87. raise TypeError(
  88. "%s() argument 2 should be a list, not a "
  89. "string" % type(self).__name__
  90. )
  91. else:
  92. list.__init__(self, children)
  93. self._label = node
  94. # ////////////////////////////////////////////////////////////
  95. # Comparison operators
  96. # ////////////////////////////////////////////////////////////
  97. def __eq__(self, other):
  98. return self.__class__ is other.__class__ and (self._label, list(self)) == (
  99. other._label,
  100. list(other),
  101. )
  102. def __lt__(self, other):
  103. if not isinstance(other, Tree):
  104. # raise_unorderable_types("<", self, other)
  105. # Sometimes children can be pure strings,
  106. # so we need to be able to compare with non-trees:
  107. return self.__class__.__name__ < other.__class__.__name__
  108. elif self.__class__ is other.__class__:
  109. return (self._label, list(self)) < (other._label, list(other))
  110. else:
  111. return self.__class__.__name__ < other.__class__.__name__
  112. # @total_ordering doesn't work here, since the class inherits from a builtin class
  113. __ne__ = lambda self, other: not self == other
  114. __gt__ = lambda self, other: not (self < other or self == other)
  115. __le__ = lambda self, other: self < other or self == other
  116. __ge__ = lambda self, other: not self < other
  117. # ////////////////////////////////////////////////////////////
  118. # Disabled list operations
  119. # ////////////////////////////////////////////////////////////
  120. def __mul__(self, v):
  121. raise TypeError('Tree does not support multiplication')
  122. def __rmul__(self, v):
  123. raise TypeError('Tree does not support multiplication')
  124. def __add__(self, v):
  125. raise TypeError('Tree does not support addition')
  126. def __radd__(self, v):
  127. raise TypeError('Tree does not support addition')
  128. # ////////////////////////////////////////////////////////////
  129. # Indexing (with support for tree positions)
  130. # ////////////////////////////////////////////////////////////
  131. def __getitem__(self, index):
  132. if isinstance(index, (int, slice)):
  133. return list.__getitem__(self, index)
  134. elif isinstance(index, (list, tuple)):
  135. if len(index) == 0:
  136. return self
  137. elif len(index) == 1:
  138. return self[index[0]]
  139. else:
  140. return self[index[0]][index[1:]]
  141. else:
  142. raise TypeError(
  143. "%s indices must be integers, not %s"
  144. % (type(self).__name__, type(index).__name__)
  145. )
  146. def __setitem__(self, index, value):
  147. if isinstance(index, (int, slice)):
  148. return list.__setitem__(self, index, value)
  149. elif isinstance(index, (list, tuple)):
  150. if len(index) == 0:
  151. raise IndexError('The tree position () may not be ' 'assigned to.')
  152. elif len(index) == 1:
  153. self[index[0]] = value
  154. else:
  155. self[index[0]][index[1:]] = value
  156. else:
  157. raise TypeError(
  158. "%s indices must be integers, not %s"
  159. % (type(self).__name__, type(index).__name__)
  160. )
  161. def __delitem__(self, index):
  162. if isinstance(index, (int, slice)):
  163. return list.__delitem__(self, index)
  164. elif isinstance(index, (list, tuple)):
  165. if len(index) == 0:
  166. raise IndexError('The tree position () may not be deleted.')
  167. elif len(index) == 1:
  168. del self[index[0]]
  169. else:
  170. del self[index[0]][index[1:]]
  171. else:
  172. raise TypeError(
  173. "%s indices must be integers, not %s"
  174. % (type(self).__name__, type(index).__name__)
  175. )
  176. # ////////////////////////////////////////////////////////////
  177. # Basic tree operations
  178. # ////////////////////////////////////////////////////////////
  179. def _get_node(self):
  180. """Outdated method to access the node value; use the label() method instead."""
  181. raise NotImplementedError("Use label() to access a node label.")
  182. def _set_node(self, value):
  183. """Outdated method to set the node value; use the set_label() method instead."""
  184. raise NotImplementedError("Use set_label() method to set a node label.")
  185. node = property(_get_node, _set_node)
  186. def label(self):
  187. """
  188. Return the node label of the tree.
  189. >>> t = Tree.fromstring('(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))')
  190. >>> t.label()
  191. 'S'
  192. :return: the node label (typically a string)
  193. :rtype: any
  194. """
  195. return self._label
  196. def set_label(self, label):
  197. """
  198. Set the node label of the tree.
  199. >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
  200. >>> t.set_label("T")
  201. >>> print(t)
  202. (T (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))
  203. :param label: the node label (typically a string)
  204. :type label: any
  205. """
  206. self._label = label
  207. def leaves(self):
  208. """
  209. Return the leaves of the tree.
  210. >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
  211. >>> t.leaves()
  212. ['the', 'dog', 'chased', 'the', 'cat']
  213. :return: a list containing this tree's leaves.
  214. The order reflects the order of the
  215. leaves in the tree's hierarchical structure.
  216. :rtype: list
  217. """
  218. leaves = []
  219. for child in self:
  220. if isinstance(child, Tree):
  221. leaves.extend(child.leaves())
  222. else:
  223. leaves.append(child)
  224. return leaves
  225. def flatten(self):
  226. """
  227. Return a flat version of the tree, with all non-root non-terminals removed.
  228. >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
  229. >>> print(t.flatten())
  230. (S the dog chased the cat)
  231. :return: a tree consisting of this tree's root connected directly to
  232. its leaves, omitting all intervening non-terminal nodes.
  233. :rtype: Tree
  234. """
  235. return Tree(self.label(), self.leaves())
  236. def height(self):
  237. """
  238. Return the height of the tree.
  239. >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
  240. >>> t.height()
  241. 5
  242. >>> print(t[0,0])
  243. (D the)
  244. >>> t[0,0].height()
  245. 2
  246. :return: The height of this tree. The height of a tree
  247. containing no children is 1; the height of a tree
  248. containing only leaves is 2; and the height of any other
  249. tree is one plus the maximum of its children's
  250. heights.
  251. :rtype: int
  252. """
  253. max_child_height = 0
  254. for child in self:
  255. if isinstance(child, Tree):
  256. max_child_height = max(max_child_height, child.height())
  257. else:
  258. max_child_height = max(max_child_height, 1)
  259. return 1 + max_child_height
  260. def treepositions(self, order='preorder'):
  261. """
  262. >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
  263. >>> t.treepositions() # doctest: +ELLIPSIS
  264. [(), (0,), (0, 0), (0, 0, 0), (0, 1), (0, 1, 0), (1,), (1, 0), (1, 0, 0), ...]
  265. >>> for pos in t.treepositions('leaves'):
  266. ... t[pos] = t[pos][::-1].upper()
  267. >>> print(t)
  268. (S (NP (D EHT) (N GOD)) (VP (V DESAHC) (NP (D EHT) (N TAC))))
  269. :param order: One of: ``preorder``, ``postorder``, ``bothorder``,
  270. ``leaves``.
  271. """
  272. positions = []
  273. if order in ('preorder', 'bothorder'):
  274. positions.append(())
  275. for i, child in enumerate(self):
  276. if isinstance(child, Tree):
  277. childpos = child.treepositions(order)
  278. positions.extend((i,) + p for p in childpos)
  279. else:
  280. positions.append((i,))
  281. if order in ('postorder', 'bothorder'):
  282. positions.append(())
  283. return positions
  284. def subtrees(self, filter=None):
  285. """
  286. Generate all the subtrees of this tree, optionally restricted
  287. to trees matching the filter function.
  288. >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
  289. >>> for s in t.subtrees(lambda t: t.height() == 2):
  290. ... print(s)
  291. (D the)
  292. (N dog)
  293. (V chased)
  294. (D the)
  295. (N cat)
  296. :type filter: function
  297. :param filter: the function to filter all local trees
  298. """
  299. if not filter or filter(self):
  300. yield self
  301. for child in self:
  302. if isinstance(child, Tree):
  303. for subtree in child.subtrees(filter):
  304. yield subtree
  305. def productions(self):
  306. """
  307. Generate the productions that correspond to the non-terminal nodes of the tree.
  308. For each subtree of the form (P: C1 C2 ... Cn) this produces a production of the
  309. form P -> C1 C2 ... Cn.
  310. >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
  311. >>> t.productions()
  312. [S -> NP VP, NP -> D N, D -> 'the', N -> 'dog', VP -> V NP, V -> 'chased',
  313. NP -> D N, D -> 'the', N -> 'cat']
  314. :rtype: list(Production)
  315. """
  316. if not isinstance(self._label, string_types):
  317. raise TypeError(
  318. 'Productions can only be generated from trees having node labels that are strings'
  319. )
  320. prods = [Production(Nonterminal(self._label), _child_names(self))]
  321. for child in self:
  322. if isinstance(child, Tree):
  323. prods += child.productions()
  324. return prods
  325. def pos(self):
  326. """
  327. Return a sequence of pos-tagged words extracted from the tree.
  328. >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
  329. >>> t.pos()
  330. [('the', 'D'), ('dog', 'N'), ('chased', 'V'), ('the', 'D'), ('cat', 'N')]
  331. :return: a list of tuples containing leaves and pre-terminals (part-of-speech tags).
  332. The order reflects the order of the leaves in the tree's hierarchical structure.
  333. :rtype: list(tuple)
  334. """
  335. pos = []
  336. for child in self:
  337. if isinstance(child, Tree):
  338. pos.extend(child.pos())
  339. else:
  340. pos.append((child, self._label))
  341. return pos
  342. def leaf_treeposition(self, index):
  343. """
  344. :return: The tree position of the ``index``-th leaf in this
  345. tree. I.e., if ``tp=self.leaf_treeposition(i)``, then
  346. ``self[tp]==self.leaves()[i]``.
  347. :raise IndexError: If this tree contains fewer than ``index+1``
  348. leaves, or if ``index<0``.
  349. """
  350. if index < 0:
  351. raise IndexError('index must be non-negative')
  352. stack = [(self, ())]
  353. while stack:
  354. value, treepos = stack.pop()
  355. if not isinstance(value, Tree):
  356. if index == 0:
  357. return treepos
  358. else:
  359. index -= 1
  360. else:
  361. for i in range(len(value) - 1, -1, -1):
  362. stack.append((value[i], treepos + (i,)))
  363. raise IndexError('index must be less than or equal to len(self)')
  364. def treeposition_spanning_leaves(self, start, end):
  365. """
  366. :return: The tree position of the lowest descendant of this
  367. tree that dominates ``self.leaves()[start:end]``.
  368. :raise ValueError: if ``end <= start``
  369. """
  370. if end <= start:
  371. raise ValueError('end must be greater than start')
  372. # Find the tree positions of the start & end leaves, and
  373. # take the longest common subsequence.
  374. start_treepos = self.leaf_treeposition(start)
  375. end_treepos = self.leaf_treeposition(end - 1)
  376. # Find the first index where they mismatch:
  377. for i in range(len(start_treepos)):
  378. if i == len(end_treepos) or start_treepos[i] != end_treepos[i]:
  379. return start_treepos[:i]
  380. return start_treepos
  381. # ////////////////////////////////////////////////////////////
  382. # Transforms
  383. # ////////////////////////////////////////////////////////////
  384. def chomsky_normal_form(
  385. self,
  386. factor="right",
  387. horzMarkov=None,
  388. vertMarkov=0,
  389. childChar="|",
  390. parentChar="^",
  391. ):
  392. """
  393. This method can modify a tree in three ways:
  394. 1. Convert a tree into its Chomsky Normal Form (CNF)
  395. equivalent -- Every subtree has either two non-terminals
  396. or one terminal as its children. This process requires
  397. the creation of more"artificial" non-terminal nodes.
  398. 2. Markov (vertical) smoothing of children in new artificial
  399. nodes
  400. 3. Horizontal (parent) annotation of nodes
  401. :param factor: Right or left factoring method (default = "right")
  402. :type factor: str = [left|right]
  403. :param horzMarkov: Markov order for sibling smoothing in artificial nodes (None (default) = include all siblings)
  404. :type horzMarkov: int | None
  405. :param vertMarkov: Markov order for parent smoothing (0 (default) = no vertical annotation)
  406. :type vertMarkov: int | None
  407. :param childChar: A string used in construction of the artificial nodes, separating the head of the
  408. original subtree from the child nodes that have yet to be expanded (default = "|")
  409. :type childChar: str
  410. :param parentChar: A string used to separate the node representation from its vertical annotation
  411. :type parentChar: str
  412. """
  413. from nltk.treetransforms import chomsky_normal_form
  414. chomsky_normal_form(self, factor, horzMarkov, vertMarkov, childChar, parentChar)
  415. def un_chomsky_normal_form(
  416. self, expandUnary=True, childChar="|", parentChar="^", unaryChar="+"
  417. ):
  418. """
  419. This method modifies the tree in three ways:
  420. 1. Transforms a tree in Chomsky Normal Form back to its
  421. original structure (branching greater than two)
  422. 2. Removes any parent annotation (if it exists)
  423. 3. (optional) expands unary subtrees (if previously
  424. collapsed with collapseUnary(...) )
  425. :param expandUnary: Flag to expand unary or not (default = True)
  426. :type expandUnary: bool
  427. :param childChar: A string separating the head node from its children in an artificial node (default = "|")
  428. :type childChar: str
  429. :param parentChar: A sting separating the node label from its parent annotation (default = "^")
  430. :type parentChar: str
  431. :param unaryChar: A string joining two non-terminals in a unary production (default = "+")
  432. :type unaryChar: str
  433. """
  434. from nltk.treetransforms import un_chomsky_normal_form
  435. un_chomsky_normal_form(self, expandUnary, childChar, parentChar, unaryChar)
  436. def collapse_unary(self, collapsePOS=False, collapseRoot=False, joinChar="+"):
  437. """
  438. Collapse subtrees with a single child (ie. unary productions)
  439. into a new non-terminal (Tree node) joined by 'joinChar'.
  440. This is useful when working with algorithms that do not allow
  441. unary productions, and completely removing the unary productions
  442. would require loss of useful information. The Tree is modified
  443. directly (since it is passed by reference) and no value is returned.
  444. :param collapsePOS: 'False' (default) will not collapse the parent of leaf nodes (ie.
  445. Part-of-Speech tags) since they are always unary productions
  446. :type collapsePOS: bool
  447. :param collapseRoot: 'False' (default) will not modify the root production
  448. if it is unary. For the Penn WSJ treebank corpus, this corresponds
  449. to the TOP -> productions.
  450. :type collapseRoot: bool
  451. :param joinChar: A string used to connect collapsed node values (default = "+")
  452. :type joinChar: str
  453. """
  454. from nltk.treetransforms import collapse_unary
  455. collapse_unary(self, collapsePOS, collapseRoot, joinChar)
  456. # ////////////////////////////////////////////////////////////
  457. # Convert, copy
  458. # ////////////////////////////////////////////////////////////
  459. @classmethod
  460. def convert(cls, tree):
  461. """
  462. Convert a tree between different subtypes of Tree. ``cls`` determines
  463. which class will be used to encode the new tree.
  464. :type tree: Tree
  465. :param tree: The tree that should be converted.
  466. :return: The new Tree.
  467. """
  468. if isinstance(tree, Tree):
  469. children = [cls.convert(child) for child in tree]
  470. return cls(tree._label, children)
  471. else:
  472. return tree
  473. def copy(self, deep=False):
  474. if not deep:
  475. return type(self)(self._label, self)
  476. else:
  477. return type(self).convert(self)
  478. def _frozen_class(self):
  479. return ImmutableTree
  480. def freeze(self, leaf_freezer=None):
  481. frozen_class = self._frozen_class()
  482. if leaf_freezer is None:
  483. newcopy = frozen_class.convert(self)
  484. else:
  485. newcopy = self.copy(deep=True)
  486. for pos in newcopy.treepositions('leaves'):
  487. newcopy[pos] = leaf_freezer(newcopy[pos])
  488. newcopy = frozen_class.convert(newcopy)
  489. hash(newcopy) # Make sure the leaves are hashable.
  490. return newcopy
  491. # ////////////////////////////////////////////////////////////
  492. # Parsing
  493. # ////////////////////////////////////////////////////////////
  494. @classmethod
  495. def fromstring(
  496. cls,
  497. s,
  498. brackets='()',
  499. read_node=None,
  500. read_leaf=None,
  501. node_pattern=None,
  502. leaf_pattern=None,
  503. remove_empty_top_bracketing=False,
  504. ):
  505. """
  506. Read a bracketed tree string and return the resulting tree.
  507. Trees are represented as nested brackettings, such as::
  508. (S (NP (NNP John)) (VP (V runs)))
  509. :type s: str
  510. :param s: The string to read
  511. :type brackets: str (length=2)
  512. :param brackets: The bracket characters used to mark the
  513. beginning and end of trees and subtrees.
  514. :type read_node: function
  515. :type read_leaf: function
  516. :param read_node, read_leaf: If specified, these functions
  517. are applied to the substrings of ``s`` corresponding to
  518. nodes and leaves (respectively) to obtain the values for
  519. those nodes and leaves. They should have the following
  520. signature:
  521. read_node(str) -> value
  522. For example, these functions could be used to process nodes
  523. and leaves whose values should be some type other than
  524. string (such as ``FeatStruct``).
  525. Note that by default, node strings and leaf strings are
  526. delimited by whitespace and brackets; to override this
  527. default, use the ``node_pattern`` and ``leaf_pattern``
  528. arguments.
  529. :type node_pattern: str
  530. :type leaf_pattern: str
  531. :param node_pattern, leaf_pattern: Regular expression patterns
  532. used to find node and leaf substrings in ``s``. By
  533. default, both nodes patterns are defined to match any
  534. sequence of non-whitespace non-bracket characters.
  535. :type remove_empty_top_bracketing: bool
  536. :param remove_empty_top_bracketing: If the resulting tree has
  537. an empty node label, and is length one, then return its
  538. single child instead. This is useful for treebank trees,
  539. which sometimes contain an extra level of bracketing.
  540. :return: A tree corresponding to the string representation ``s``.
  541. If this class method is called using a subclass of Tree,
  542. then it will return a tree of that type.
  543. :rtype: Tree
  544. """
  545. if not isinstance(brackets, string_types) or len(brackets) != 2:
  546. raise TypeError('brackets must be a length-2 string')
  547. if re.search('\s', brackets):
  548. raise TypeError('whitespace brackets not allowed')
  549. # Construct a regexp that will tokenize the string.
  550. open_b, close_b = brackets
  551. open_pattern, close_pattern = (re.escape(open_b), re.escape(close_b))
  552. if node_pattern is None:
  553. node_pattern = '[^\s%s%s]+' % (open_pattern, close_pattern)
  554. if leaf_pattern is None:
  555. leaf_pattern = '[^\s%s%s]+' % (open_pattern, close_pattern)
  556. token_re = re.compile(
  557. '%s\s*(%s)?|%s|(%s)'
  558. % (open_pattern, node_pattern, close_pattern, leaf_pattern)
  559. )
  560. # Walk through each token, updating a stack of trees.
  561. stack = [(None, [])] # list of (node, children) tuples
  562. for match in token_re.finditer(s):
  563. token = match.group()
  564. # Beginning of a tree/subtree
  565. if token[0] == open_b:
  566. if len(stack) == 1 and len(stack[0][1]) > 0:
  567. cls._parse_error(s, match, 'end-of-string')
  568. label = token[1:].lstrip()
  569. if read_node is not None:
  570. label = read_node(label)
  571. stack.append((label, []))
  572. # End of a tree/subtree
  573. elif token == close_b:
  574. if len(stack) == 1:
  575. if len(stack[0][1]) == 0:
  576. cls._parse_error(s, match, open_b)
  577. else:
  578. cls._parse_error(s, match, 'end-of-string')
  579. label, children = stack.pop()
  580. stack[-1][1].append(cls(label, children))
  581. # Leaf node
  582. else:
  583. if len(stack) == 1:
  584. cls._parse_error(s, match, open_b)
  585. if read_leaf is not None:
  586. token = read_leaf(token)
  587. stack[-1][1].append(token)
  588. # check that we got exactly one complete tree.
  589. if len(stack) > 1:
  590. cls._parse_error(s, 'end-of-string', close_b)
  591. elif len(stack[0][1]) == 0:
  592. cls._parse_error(s, 'end-of-string', open_b)
  593. else:
  594. assert stack[0][0] is None
  595. assert len(stack[0][1]) == 1
  596. tree = stack[0][1][0]
  597. # If the tree has an extra level with node='', then get rid of
  598. # it. E.g.: "((S (NP ...) (VP ...)))"
  599. if remove_empty_top_bracketing and tree._label == '' and len(tree) == 1:
  600. tree = tree[0]
  601. # return the tree.
  602. return tree
  603. @classmethod
  604. def _parse_error(cls, s, match, expecting):
  605. """
  606. Display a friendly error message when parsing a tree string fails.
  607. :param s: The string we're parsing.
  608. :param match: regexp match of the problem token.
  609. :param expecting: what we expected to see instead.
  610. """
  611. # Construct a basic error message
  612. if match == 'end-of-string':
  613. pos, token = len(s), 'end-of-string'
  614. else:
  615. pos, token = match.start(), match.group()
  616. msg = '%s.read(): expected %r but got %r\n%sat index %d.' % (
  617. cls.__name__,
  618. expecting,
  619. token,
  620. ' ' * 12,
  621. pos,
  622. )
  623. # Add a display showing the error token itsels:
  624. s = s.replace('\n', ' ').replace('\t', ' ')
  625. offset = pos
  626. if len(s) > pos + 10:
  627. s = s[: pos + 10] + '...'
  628. if pos > 10:
  629. s = '...' + s[pos - 10 :]
  630. offset = 13
  631. msg += '\n%s"%s"\n%s^' % (' ' * 16, s, ' ' * (17 + offset))
  632. raise ValueError(msg)
  633. # ////////////////////////////////////////////////////////////
  634. # Visualization & String Representation
  635. # ////////////////////////////////////////////////////////////
  636. def draw(self):
  637. """
  638. Open a new window containing a graphical diagram of this tree.
  639. """
  640. from nltk.draw.tree import draw_trees
  641. draw_trees(self)
  642. def pretty_print(self, sentence=None, highlight=(), stream=None, **kwargs):
  643. """
  644. Pretty-print this tree as ASCII or Unicode art.
  645. For explanation of the arguments, see the documentation for
  646. `nltk.treeprettyprinter.TreePrettyPrinter`.
  647. """
  648. from nltk.treeprettyprinter import TreePrettyPrinter
  649. print(TreePrettyPrinter(self, sentence, highlight).text(**kwargs), file=stream)
  650. def __repr__(self):
  651. childstr = ", ".join(unicode_repr(c) for c in self)
  652. return '%s(%s, [%s])' % (
  653. type(self).__name__,
  654. unicode_repr(self._label),
  655. childstr,
  656. )
  657. def _repr_png_(self):
  658. """
  659. Draws and outputs in PNG for ipython.
  660. PNG is used instead of PDF, since it can be displayed in the qt console and
  661. has wider browser support.
  662. """
  663. import os
  664. import base64
  665. import subprocess
  666. import tempfile
  667. from nltk.draw.tree import tree_to_treesegment
  668. from nltk.draw.util import CanvasFrame
  669. from nltk.internals import find_binary
  670. _canvas_frame = CanvasFrame()
  671. widget = tree_to_treesegment(_canvas_frame.canvas(), self)
  672. _canvas_frame.add_widget(widget)
  673. x, y, w, h = widget.bbox()
  674. # print_to_file uses scrollregion to set the width and height of the pdf.
  675. _canvas_frame.canvas()['scrollregion'] = (0, 0, w, h)
  676. with tempfile.NamedTemporaryFile() as file:
  677. in_path = '{0:}.ps'.format(file.name)
  678. out_path = '{0:}.png'.format(file.name)
  679. _canvas_frame.print_to_file(in_path)
  680. _canvas_frame.destroy_widget(widget)
  681. subprocess.call(
  682. [
  683. find_binary(
  684. 'gs',
  685. binary_names=['gswin32c.exe', 'gswin64c.exe'],
  686. env_vars=['PATH'],
  687. verbose=False,
  688. )
  689. ]
  690. + '-q -dEPSCrop -sDEVICE=png16m -r90 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -dSAFER -dBATCH -dNOPAUSE -sOutputFile={0:} {1:}'.format(
  691. out_path, in_path
  692. ).split()
  693. )
  694. with open(out_path, 'rb') as sr:
  695. res = sr.read()
  696. os.remove(in_path)
  697. os.remove(out_path)
  698. return base64.b64encode(res).decode()
  699. def __str__(self):
  700. return self.pformat()
  701. def pprint(self, **kwargs):
  702. """
  703. Print a string representation of this Tree to 'stream'
  704. """
  705. if "stream" in kwargs:
  706. stream = kwargs["stream"]
  707. del kwargs["stream"]
  708. else:
  709. stream = None
  710. print(self.pformat(**kwargs), file=stream)
  711. def pformat(self, margin=70, indent=0, nodesep='', parens='()', quotes=False):
  712. """
  713. :return: A pretty-printed string representation of this tree.
  714. :rtype: str
  715. :param margin: The right margin at which to do line-wrapping.
  716. :type margin: int
  717. :param indent: The indentation level at which printing
  718. begins. This number is used to decide how far to indent
  719. subsequent lines.
  720. :type indent: int
  721. :param nodesep: A string that is used to separate the node
  722. from the children. E.g., the default value ``':'`` gives
  723. trees like ``(S: (NP: I) (VP: (V: saw) (NP: it)))``.
  724. """
  725. # Try writing it on one line.
  726. s = self._pformat_flat(nodesep, parens, quotes)
  727. if len(s) + indent < margin:
  728. return s
  729. # If it doesn't fit on one line, then write it on multi-lines.
  730. if isinstance(self._label, string_types):
  731. s = '%s%s%s' % (parens[0], self._label, nodesep)
  732. else:
  733. s = '%s%s%s' % (parens[0], unicode_repr(self._label), nodesep)
  734. for child in self:
  735. if isinstance(child, Tree):
  736. s += (
  737. '\n'
  738. + ' ' * (indent + 2)
  739. + child.pformat(margin, indent + 2, nodesep, parens, quotes)
  740. )
  741. elif isinstance(child, tuple):
  742. s += '\n' + ' ' * (indent + 2) + "/".join(child)
  743. elif isinstance(child, string_types) and not quotes:
  744. s += '\n' + ' ' * (indent + 2) + '%s' % child
  745. else:
  746. s += '\n' + ' ' * (indent + 2) + unicode_repr(child)
  747. return s + parens[1]
  748. def pformat_latex_qtree(self):
  749. r"""
  750. Returns a representation of the tree compatible with the
  751. LaTeX qtree package. This consists of the string ``\Tree``
  752. followed by the tree represented in bracketed notation.
  753. For example, the following result was generated from a parse tree of
  754. the sentence ``The announcement astounded us``::
  755. \Tree [.I'' [.N'' [.D The ] [.N' [.N announcement ] ] ]
  756. [.I' [.V'' [.V' [.V astounded ] [.N'' [.N' [.N us ] ] ] ] ] ] ]
  757. See http://www.ling.upenn.edu/advice/latex.html for the LaTeX
  758. style file for the qtree package.
  759. :return: A latex qtree representation of this tree.
  760. :rtype: str
  761. """
  762. reserved_chars = re.compile('([#\$%&~_\{\}])')
  763. pformat = self.pformat(indent=6, nodesep='', parens=('[.', ' ]'))
  764. return r'\Tree ' + re.sub(reserved_chars, r'\\\1', pformat)
  765. def _pformat_flat(self, nodesep, parens, quotes):
  766. childstrs = []
  767. for child in self:
  768. if isinstance(child, Tree):
  769. childstrs.append(child._pformat_flat(nodesep, parens, quotes))
  770. elif isinstance(child, tuple):
  771. childstrs.append("/".join(child))
  772. elif isinstance(child, string_types) and not quotes:
  773. childstrs.append('%s' % child)
  774. else:
  775. childstrs.append(unicode_repr(child))
  776. if isinstance(self._label, string_types):
  777. return '%s%s%s %s%s' % (
  778. parens[0],
  779. self._label,
  780. nodesep,
  781. " ".join(childstrs),
  782. parens[1],
  783. )
  784. else:
  785. return '%s%s%s %s%s' % (
  786. parens[0],
  787. unicode_repr(self._label),
  788. nodesep,
  789. " ".join(childstrs),
  790. parens[1],
  791. )
  792. class ImmutableTree(Tree):
  793. def __init__(self, node, children=None):
  794. super(ImmutableTree, self).__init__(node, children)
  795. # Precompute our hash value. This ensures that we're really
  796. # immutable. It also means we only have to calculate it once.
  797. try:
  798. self._hash = hash((self._label, tuple(self)))
  799. except (TypeError, ValueError):
  800. raise ValueError(
  801. "%s: node value and children " "must be immutable" % type(self).__name__
  802. )
  803. def __setitem__(self, index, value):
  804. raise ValueError('%s may not be modified' % type(self).__name__)
  805. def __setslice__(self, i, j, value):
  806. raise ValueError('%s may not be modified' % type(self).__name__)
  807. def __delitem__(self, index):
  808. raise ValueError('%s may not be modified' % type(self).__name__)
  809. def __delslice__(self, i, j):
  810. raise ValueError('%s may not be modified' % type(self).__name__)
  811. def __iadd__(self, other):
  812. raise ValueError('%s may not be modified' % type(self).__name__)
  813. def __imul__(self, other):
  814. raise ValueError('%s may not be modified' % type(self).__name__)
  815. def append(self, v):
  816. raise ValueError('%s may not be modified' % type(self).__name__)
  817. def extend(self, v):
  818. raise ValueError('%s may not be modified' % type(self).__name__)
  819. def pop(self, v=None):
  820. raise ValueError('%s may not be modified' % type(self).__name__)
  821. def remove(self, v):
  822. raise ValueError('%s may not be modified' % type(self).__name__)
  823. def reverse(self):
  824. raise ValueError('%s may not be modified' % type(self).__name__)
  825. def sort(self):
  826. raise ValueError('%s may not be modified' % type(self).__name__)
  827. def __hash__(self):
  828. return self._hash
  829. def set_label(self, value):
  830. """
  831. Set the node label. This will only succeed the first time the
  832. node label is set, which should occur in ImmutableTree.__init__().
  833. """
  834. if hasattr(self, '_label'):
  835. raise ValueError('%s may not be modified' % type(self).__name__)
  836. self._label = value
  837. ######################################################################
  838. ## Parented trees
  839. ######################################################################
  840. @add_metaclass(ABCMeta)
  841. class AbstractParentedTree(Tree):
  842. """
  843. An abstract base class for a ``Tree`` that automatically maintains
  844. pointers to parent nodes. These parent pointers are updated
  845. whenever any change is made to a tree's structure. Two subclasses
  846. are currently defined:
  847. - ``ParentedTree`` is used for tree structures where each subtree
  848. has at most one parent. This class should be used in cases
  849. where there is no"sharing" of subtrees.
  850. - ``MultiParentedTree`` is used for tree structures where a
  851. subtree may have zero or more parents. This class should be
  852. used in cases where subtrees may be shared.
  853. Subclassing
  854. ===========
  855. The ``AbstractParentedTree`` class redefines all operations that
  856. modify a tree's structure to call two methods, which are used by
  857. subclasses to update parent information:
  858. - ``_setparent()`` is called whenever a new child is added.
  859. - ``_delparent()`` is called whenever a child is removed.
  860. """
  861. def __init__(self, node, children=None):
  862. super(AbstractParentedTree, self).__init__(node, children)
  863. # If children is None, the tree is read from node, and
  864. # all parents will be set during parsing.
  865. if children is not None:
  866. # Otherwise we have to set the parent of the children.
  867. # Iterate over self, and *not* children, because children
  868. # might be an iterator.
  869. for i, child in enumerate(self):
  870. if isinstance(child, Tree):
  871. self._setparent(child, i, dry_run=True)
  872. for i, child in enumerate(self):
  873. if isinstance(child, Tree):
  874. self._setparent(child, i)
  875. # ////////////////////////////////////////////////////////////
  876. # Parent management
  877. # ////////////////////////////////////////////////////////////
  878. @abstractmethod
  879. def _setparent(self, child, index, dry_run=False):
  880. """
  881. Update the parent pointer of ``child`` to point to ``self``. This
  882. method is only called if the type of ``child`` is ``Tree``;
  883. i.e., it is not called when adding a leaf to a tree. This method
  884. is always called before the child is actually added to the
  885. child list of ``self``.
  886. :type child: Tree
  887. :type index: int
  888. :param index: The index of ``child`` in ``self``.
  889. :raise TypeError: If ``child`` is a tree with an impropriate
  890. type. Typically, if ``child`` is a tree, then its type needs
  891. to match the type of ``self``. This prevents mixing of
  892. different tree types (single-parented, multi-parented, and
  893. non-parented).
  894. :param dry_run: If true, the don't actually set the child's
  895. parent pointer; just check for any error conditions, and
  896. raise an exception if one is found.
  897. """
  898. @abstractmethod
  899. def _delparent(self, child, index):
  900. """
  901. Update the parent pointer of ``child`` to not point to self. This
  902. method is only called if the type of ``child`` is ``Tree``; i.e., it
  903. is not called when removing a leaf from a tree. This method
  904. is always called before the child is actually removed from the
  905. child list of ``self``.
  906. :type child: Tree
  907. :type index: int
  908. :param index: The index of ``child`` in ``self``.
  909. """
  910. # ////////////////////////////////////////////////////////////
  911. # Methods that add/remove children
  912. # ////////////////////////////////////////////////////////////
  913. # Every method that adds or removes a child must make
  914. # appropriate calls to _setparent() and _delparent().
  915. def __delitem__(self, index):
  916. # del ptree[start:stop]
  917. if isinstance(index, slice):
  918. start, stop, step = slice_bounds(self, index, allow_step=True)
  919. # Clear all the children pointers.
  920. for i in range(start, stop, step):
  921. if isinstance(self[i], Tree):
  922. self._delparent(self[i], i)
  923. # Delete the children from our child list.
  924. super(AbstractParentedTree, self).__delitem__(index)
  925. # del ptree[i]
  926. elif isinstance(index, int):
  927. if index < 0:
  928. index += len(self)
  929. if index < 0:
  930. raise IndexError('index out of range')
  931. # Clear the child's parent pointer.
  932. if isinstance(self[index], Tree):
  933. self._delparent(self[index], index)
  934. # Remove the child from our child list.
  935. super(AbstractParentedTree, self).__delitem__(index)
  936. elif isinstance(index, (list, tuple)):
  937. # del ptree[()]
  938. if len(index) == 0:
  939. raise IndexError('The tree position () may not be deleted.')
  940. # del ptree[(i,)]
  941. elif len(index) == 1:
  942. del self[index[0]]
  943. # del ptree[i1, i2, i3]
  944. else:
  945. del self[index[0]][index[1:]]
  946. else:
  947. raise TypeError(
  948. "%s indices must be integers, not %s"
  949. % (type(self).__name__, type(index).__name__)
  950. )
  951. def __setitem__(self, index, value):
  952. # ptree[start:stop] = value
  953. if isinstance(index, slice):
  954. start, stop, step = slice_bounds(self, index, allow_step=True)
  955. # make a copy of value, in case it's an iterator
  956. if not isinstance(value, (list, tuple)):
  957. value = list(value)
  958. # Check for any error conditions, so we can avoid ending
  959. # up in an inconsistent state if an error does occur.
  960. for i, child in enumerate(value):
  961. if isinstance(child, Tree):
  962. self._setparent(child, start + i * step, dry_run=True)
  963. # clear the child pointers of all parents we're removing
  964. for i in range(start, stop, step):
  965. if isinstance(self[i], Tree):
  966. self._delparent(self[i], i)
  967. # set the child pointers of the new children. We do this
  968. # after clearing *all* child pointers, in case we're e.g.
  969. # reversing the elements in a tree.
  970. for i, child in enumerate(value):
  971. if isinstance(child, Tree):
  972. self._setparent(child, start + i * step)
  973. # finally, update the content of the child list itself.
  974. super(AbstractParentedTree, self).__setitem__(index, value)
  975. # ptree[i] = value
  976. elif isinstance(index, int):
  977. if index < 0:
  978. index += len(self)
  979. if index < 0:
  980. raise IndexError('index out of range')
  981. # if the value is not changing, do nothing.
  982. if value is self[index]:
  983. return
  984. # Set the new child's parent pointer.
  985. if isinstance(value, Tree):
  986. self._setparent(value, index)
  987. # Remove the old child's parent pointer
  988. if isinstance(self[index], Tree):
  989. self._delparent(self[index], index)
  990. # Update our child list.
  991. super(AbstractParentedTree, self).__setitem__(index, value)
  992. elif isinstance(index, (list, tuple)):
  993. # ptree[()] = value
  994. if len(index) == 0:
  995. raise IndexError('The tree position () may not be assigned to.')
  996. # ptree[(i,)] = value
  997. elif len(index) == 1:
  998. self[index[0]] = value
  999. # ptree[i1, i2, i3] = value
  1000. else:
  1001. self[index[0]][index[1:]] = value
  1002. else:
  1003. raise TypeError(
  1004. "%s indices must be integers, not %s"
  1005. % (type(self).__name__, type(index).__name__)
  1006. )
  1007. def append(self, child):
  1008. if isinstance(child, Tree):
  1009. self._setparent(child, len(self))
  1010. super(AbstractParentedTree, self).append(child)
  1011. def extend(self, children):
  1012. for child in children:
  1013. if isinstance(child, Tree):
  1014. self._setparent(child, len(self))
  1015. super(AbstractParentedTree, self).append(child)
  1016. def insert(self, index, child):
  1017. # Handle negative indexes. Note that if index < -len(self),
  1018. # we do *not* raise an IndexError, unlike __getitem__. This
  1019. # is done for consistency with list.__getitem__ and list.index.
  1020. if index < 0:
  1021. index += len(self)
  1022. if index < 0:
  1023. index = 0
  1024. # Set the child's parent, and update our child list.
  1025. if isinstance(child, Tree):
  1026. self._setparent(child, index)
  1027. super(AbstractParentedTree, self).insert(index, child)
  1028. def pop(self, index=-1):
  1029. if index < 0:
  1030. index += len(self)
  1031. if index < 0:
  1032. raise IndexError('index out of range')
  1033. if isinstance(self[index], Tree):
  1034. self._delparent(self[index], index)
  1035. return super(AbstractParentedTree, self).pop(index)
  1036. # n.b.: like `list`, this is done by equality, not identity!
  1037. # To remove a specific child, use del ptree[i].
  1038. def remove(self, child):
  1039. index = self.index(child)
  1040. if isinstance(self[index], Tree):
  1041. self._delparent(self[index], index)
  1042. super(AbstractParentedTree, self).remove(child)
  1043. # We need to implement __getslice__ and friends, even though
  1044. # they're deprecated, because otherwise list.__getslice__ will get
  1045. # called (since we're subclassing from list). Just delegate to
  1046. # __getitem__ etc., but use max(0, start) and max(0, stop) because
  1047. # because negative indices are already handled *before*
  1048. # __getslice__ is called; and we don't want to double-count them.
  1049. if hasattr(list, '__getslice__'):
  1050. def __getslice__(self, start, stop):
  1051. return self.__getitem__(slice(max(0, start), max(0, stop)))
  1052. def __delslice__(self, start, stop):
  1053. return self.__delitem__(slice(max(0, start), max(0, stop)))
  1054. def __setslice__(self, start, stop, value):
  1055. return self.__setitem__(slice(max(0, start), max(0, stop)), value)
  1056. class ParentedTree(AbstractParentedTree):
  1057. """
  1058. A ``Tree`` that automatically maintains parent pointers for
  1059. single-parented trees. The following are methods for querying
  1060. the structure of a parented tree: ``parent``, ``parent_index``,
  1061. ``left_sibling``, ``right_sibling``, ``root``, ``treeposition``.
  1062. Each ``ParentedTree`` may have at most one parent. In
  1063. particular, subtrees may not be shared. Any attempt to reuse a
  1064. single ``ParentedTree`` as a child of more than one parent (or
  1065. as multiple children of the same parent) will cause a
  1066. ``ValueError`` exception to be raised.
  1067. ``ParentedTrees`` should never be used in the same tree as ``Trees``
  1068. or ``MultiParentedTrees``. Mixing tree implementations may result
  1069. in incorrect parent pointers and in ``TypeError`` exceptions.
  1070. """
  1071. def __init__(self, node, children=None):
  1072. self._parent = None
  1073. """The parent of this Tree, or None if it has no parent."""
  1074. super(ParentedTree, self).__init__(node, children)
  1075. if children is None:
  1076. # If children is None, the tree is read from node.
  1077. # After parsing, the parent of the immediate children
  1078. # will point to an intermediate tree, not self.
  1079. # We fix this by brute force:
  1080. for i, child in enumerate(self):
  1081. if isinstance(child, Tree):
  1082. child._parent = None
  1083. self._setparent(child, i)
  1084. def _frozen_class(self):
  1085. return ImmutableParentedTree
  1086. # /////////////////////////////////////////////////////////////////
  1087. # Methods
  1088. # /////////////////////////////////////////////////////////////////
  1089. def parent(self):
  1090. """The parent of this tree, or None if it has no parent."""
  1091. return self._parent
  1092. def parent_index(self):
  1093. """
  1094. The index of this tree in its parent. I.e.,
  1095. ``ptree.parent()[ptree.parent_index()] is ptree``. Note that
  1096. ``ptree.parent_index()`` is not necessarily equal to
  1097. ``ptree.parent.index(ptree)``, since the ``index()`` method
  1098. returns the first child that is equal to its argument.
  1099. """
  1100. if self._parent is None:
  1101. return None
  1102. for i, child in enumerate(self._parent):
  1103. if child is self:
  1104. return i
  1105. assert False, 'expected to find self in self._parent!'
  1106. def left_sibling(self):
  1107. """The left sibling of this tree, or None if it has none."""
  1108. parent_index = self.parent_index()
  1109. if self._parent and parent_index > 0:
  1110. return self._parent[parent_index - 1]
  1111. return None # no left sibling
  1112. def right_sibling(self):
  1113. """The right sibling of this tree, or None if it has none."""
  1114. parent_index = self.parent_index()
  1115. if self._parent and parent_index < (len(self._parent) - 1):
  1116. return self._parent[parent_index + 1]
  1117. return None # no right sibling
  1118. def root(self):
  1119. """
  1120. The root of this tree. I.e., the unique ancestor of this tree
  1121. whose parent is None. If ``ptree.parent()`` is None, then
  1122. ``ptree`` is its own root.
  1123. """
  1124. root = self
  1125. while root.parent() is not None:
  1126. root = root.parent()
  1127. return root
  1128. def treeposition(self):
  1129. """
  1130. The tree position of this tree, relative to the root of the
  1131. tree. I.e., ``ptree.root[ptree.treeposition] is ptree``.
  1132. """
  1133. if self.parent() is None:
  1134. return ()
  1135. else:
  1136. return self.parent().treeposition() + (self.parent_index(),)
  1137. # /////////////////////////////////////////////////////////////////
  1138. # Parent Management
  1139. # /////////////////////////////////////////////////////////////////
  1140. def _delparent(self, child, index):
  1141. # Sanity checks
  1142. assert isinstance(child, ParentedTree)
  1143. assert self[index] is child
  1144. assert child._parent is self
  1145. # Delete child's parent pointer.
  1146. child._parent = None
  1147. def _setparent(self, child, index, dry_run=False):
  1148. # If the child's type is incorrect, then complain.
  1149. if not isinstance(child, ParentedTree):
  1150. raise TypeError(
  1151. 'Can not insert a non-ParentedTree ' + 'into a ParentedTree'
  1152. )
  1153. # If child already has a parent, then complain.
  1154. if child._parent is not None:
  1155. raise ValueError('Can not insert a subtree that already ' 'has a parent.')
  1156. # Set child's parent pointer & index.
  1157. if not dry_run:
  1158. child._parent = self
  1159. class MultiParentedTree(AbstractParentedTree):
  1160. """
  1161. A ``Tree`` that automatically maintains parent pointers for
  1162. multi-parented trees. The following are methods for querying the
  1163. structure of a multi-parented tree: ``parents()``, ``parent_indices()``,
  1164. ``left_siblings()``, ``right_siblings()``, ``roots``, ``treepositions``.
  1165. Each ``MultiParentedTree`` may have zero or more parents. In
  1166. particular, subtrees may be shared. If a single
  1167. ``MultiParentedTree`` is used as multiple children of the same
  1168. parent, then that parent will appear multiple times in its
  1169. ``parents()`` method.
  1170. ``MultiParentedTrees`` should never be used in the same tree as
  1171. ``Trees`` or ``ParentedTrees``. Mixing tree implementations may
  1172. result in incorrect parent pointers and in ``TypeError`` exceptions.
  1173. """
  1174. def __init__(self, node, children=None):
  1175. self._parents = []
  1176. """A list of this tree's parents. This list should not
  1177. contain duplicates, even if a parent contains this tree
  1178. multiple times."""
  1179. super(MultiParentedTree, self).__init__(node, children)
  1180. if children is None:
  1181. # If children is None, the tree is read from node.
  1182. # After parsing, the parent(s) of the immediate children
  1183. # will point to an intermediate tree, not self.
  1184. # We fix this by brute force:
  1185. for i, child in enumerate(self):
  1186. if isinstance(child, Tree):
  1187. child._parents = []
  1188. self._setparent(child, i)
  1189. def _frozen_class(self):
  1190. return ImmutableMultiParentedTree
  1191. # /////////////////////////////////////////////////////////////////
  1192. # Methods
  1193. # /////////////////////////////////////////////////////////////////
  1194. def parents(self):
  1195. """
  1196. The set of parents of this tree. If this tree has no parents,
  1197. then ``parents`` is the empty set. To check if a tree is used
  1198. as multiple children of the same parent, use the
  1199. ``parent_indices()`` method.
  1200. :type: list(MultiParentedTree)
  1201. """
  1202. return list(self._parents)
  1203. def left_siblings(self):
  1204. """
  1205. A list of all left siblings of this tree, in any of its parent
  1206. trees. A tree may be its own left sibling if it is used as
  1207. multiple contiguous children of the same parent. A tree may
  1208. appear multiple times in this list if it is the left sibling
  1209. of this tree with respect to multiple parents.
  1210. :type: list(MultiParentedTree)
  1211. """
  1212. return [
  1213. parent[index - 1]
  1214. for (parent, index) in self._get_parent_indices()
  1215. if index > 0
  1216. ]
  1217. def right_siblings(self):
  1218. """
  1219. A list of all right siblings of this tree, in any of its parent
  1220. trees. A tree may be its own right sibling if it is used as
  1221. multiple contiguous children of the same parent. A tree may
  1222. appear multiple times in this list if it is the right sibling
  1223. of this tree with respect to multiple parents.
  1224. :type: list(MultiParentedTree)
  1225. """
  1226. return [
  1227. parent[index + 1]
  1228. for (parent, index) in self._get_parent_indices()
  1229. if index < (len(parent) - 1)
  1230. ]
  1231. def _get_parent_indices(self):
  1232. return [
  1233. (parent, index)
  1234. for parent in self._parents
  1235. for index, child in enumerate(parent)
  1236. if child is self
  1237. ]
  1238. def roots(self):
  1239. """
  1240. The set of all roots of this tree. This set is formed by
  1241. tracing all possible parent paths until trees with no parents
  1242. are found.
  1243. :type: list(MultiParentedTree)
  1244. """
  1245. return list(self._get_roots_helper({}).values())
  1246. def _get_roots_helper(self, result):
  1247. if self._parents:
  1248. for parent in self._parents:
  1249. parent._get_roots_helper(result)
  1250. else:
  1251. result[id(self)] = self
  1252. return result
  1253. def parent_indices(self, parent):
  1254. """
  1255. Return a list of the indices where this tree occurs as a child
  1256. of ``parent``. If this child does not occur as a child of
  1257. ``parent``, then the empty list is returned. The following is
  1258. always true::
  1259. for parent_index in ptree.parent_indices(parent):
  1260. parent[parent_index] is ptree
  1261. """
  1262. if parent not in self._parents:
  1263. return []
  1264. else:
  1265. return [index for (index, child) in enumerate(parent) if child is self]
  1266. def treepositions(self, root):
  1267. """
  1268. Return a list of all tree positions that can be used to reach
  1269. this multi-parented tree starting from ``root``. I.e., the
  1270. following is always true::
  1271. for treepos in ptree.treepositions(root):
  1272. root[treepos] is ptree
  1273. """
  1274. if self is root:
  1275. return [()]
  1276. else:
  1277. return [
  1278. treepos + (index,)
  1279. for parent in self._parents
  1280. for treepos in parent.treepositions(root)
  1281. for (index, child) in enumerate(parent)
  1282. if child is self
  1283. ]
  1284. # /////////////////////////////////////////////////////////////////
  1285. # Parent Management
  1286. # /////////////////////////////////////////////////////////////////
  1287. def _delparent(self, child, index):
  1288. # Sanity checks
  1289. assert isinstance(child, MultiParentedTree)
  1290. assert self[index] is child
  1291. assert len([p for p in child._parents if p is self]) == 1
  1292. # If the only copy of child in self is at index, then delete
  1293. # self from child's parent list.
  1294. for i, c in enumerate(self):
  1295. if c is child and i != index:
  1296. break
  1297. else:
  1298. child._parents.remove(self)
  1299. def _setparent(self, child, index, dry_run=False):
  1300. # If the child's type is incorrect, then complain.
  1301. if not isinstance(child, MultiParentedTree):
  1302. raise TypeError(
  1303. 'Can not insert a non-MultiParentedTree ' + 'into a MultiParentedTree'
  1304. )
  1305. # Add self as a parent pointer if it's not already listed.
  1306. if not dry_run:
  1307. for parent in child._parents:
  1308. if parent is self:
  1309. break
  1310. else:
  1311. child._parents.append(self)
  1312. class ImmutableParentedTree(ImmutableTree, ParentedTree):
  1313. pass
  1314. class ImmutableMultiParentedTree(ImmutableTree, MultiParentedTree):
  1315. pass
  1316. ######################################################################
  1317. ## Probabilistic trees
  1318. ######################################################################
  1319. @python_2_unicode_compatible
  1320. class ProbabilisticTree(Tree, ProbabilisticMixIn):
  1321. def __init__(self, node, children=None, **prob_kwargs):
  1322. Tree.__init__(self, node, children)
  1323. ProbabilisticMixIn.__init__(self, **prob_kwargs)
  1324. # We have to patch up these methods to make them work right:
  1325. def _frozen_class(self):
  1326. return ImmutableProbabilisticTree
  1327. def __repr__(self):
  1328. return '%s (p=%r)' % (Tree.unicode_repr(self), self.prob())
  1329. def __str__(self):
  1330. return '%s (p=%.6g)' % (self.pformat(margin=60), self.prob())
  1331. def copy(self, deep=False):
  1332. if not deep:
  1333. return type(self)(self._label, self, prob=self.prob())
  1334. else:
  1335. return type(self).convert(self)
  1336. @classmethod
  1337. def convert(cls, val):
  1338. if isinstance(val, Tree):
  1339. children = [cls.convert(child) for child in val]
  1340. if isinstance(val, ProbabilisticMixIn):
  1341. return cls(val._label, children, prob=val.prob())
  1342. else:
  1343. return cls(val._label, children, prob=1.0)
  1344. else:
  1345. return val
  1346. def __eq__(self, other):
  1347. return self.__class__ is other.__class__ and (
  1348. self._label,
  1349. list(self),
  1350. self.prob(),
  1351. ) == (other._label, list(other), other.prob())
  1352. def __lt__(self, other):
  1353. if not isinstance(other, Tree):
  1354. raise_unorderable_types("<", self, other)
  1355. if self.__class__ is other.__class__:
  1356. return (self._label, list(self), self.prob()) < (
  1357. other._label,
  1358. list(other),
  1359. other.prob(),
  1360. )
  1361. else:
  1362. return self.__class__.__name__ < other.__class__.__name__
  1363. @python_2_unicode_compatible
  1364. class ImmutableProbabilisticTree(ImmutableTree, ProbabilisticMixIn):
  1365. def __init__(self, node, children=None, **prob_kwargs):
  1366. ImmutableTree.__init__(self, node, children)
  1367. ProbabilisticMixIn.__init__(self, **prob_kwargs)
  1368. self._hash = hash((self._label, tuple(self), self.prob()))
  1369. # We have to patch up these methods to make them work right:
  1370. def _frozen_class(self):
  1371. return ImmutableProbabilisticTree
  1372. def __repr__(self):
  1373. return '%s [%s]' % (Tree.unicode_repr(self), self.prob())
  1374. def __str__(self):
  1375. return '%s [%s]' % (self.pformat(margin=60), self.prob())
  1376. def copy(self, deep=False):
  1377. if not deep:
  1378. return type(self)(self._label, self, prob=self.prob())
  1379. else:
  1380. return type(self).convert(self)
  1381. @classmethod
  1382. def convert(cls, val):
  1383. if isinstance(val, Tree):
  1384. children = [cls.convert(child) for child in val]
  1385. if isinstance(val, ProbabilisticMixIn):
  1386. return cls(val._label, children, prob=val.prob())
  1387. else:
  1388. return cls(val._label, children, prob=1.0)
  1389. else:
  1390. return val
  1391. def _child_names(tree):
  1392. names = []
  1393. for child in tree:
  1394. if isinstance(child, Tree):
  1395. names.append(Nonterminal(child._label))
  1396. else:
  1397. names.append(child)
  1398. return names
  1399. ######################################################################
  1400. ## Parsing
  1401. ######################################################################
  1402. def bracket_parse(s):
  1403. """
  1404. Use Tree.read(s, remove_empty_top_bracketing=True) instead.
  1405. """
  1406. raise NameError("Use Tree.read(s, remove_empty_top_bracketing=True) instead.")
  1407. def sinica_parse(s):
  1408. """
  1409. Parse a Sinica Treebank string and return a tree. Trees are represented as nested brackettings,
  1410. as shown in the following example (X represents a Chinese character):
  1411. S(goal:NP(Head:Nep:XX)|theme:NP(Head:Nhaa:X)|quantity:Dab:X|Head:VL2:X)#0(PERIODCATEGORY)
  1412. :return: A tree corresponding to the string representation.
  1413. :rtype: Tree
  1414. :param s: The string to be converted
  1415. :type s: str
  1416. """
  1417. tokens = re.split(r'([()| ])', s)
  1418. for i in range(len(tokens)):
  1419. if tokens[i] == '(':
  1420. tokens[i - 1], tokens[i] = (
  1421. tokens[i],
  1422. tokens[i - 1],
  1423. ) # pull nonterminal inside parens
  1424. elif ':' in tokens[i]:
  1425. fields = tokens[i].split(':')
  1426. if len(fields) == 2: # non-terminal
  1427. tokens[i] = fields[1]
  1428. else:
  1429. tokens[i] = "(" + fields[-2] + " " + fields[-1] + ")"
  1430. elif tokens[i] == '|':
  1431. tokens[i] = ''
  1432. treebank_string = " ".join(tokens)
  1433. return Tree.fromstring(treebank_string, remove_empty_top_bracketing=True)
  1434. # s = re.sub(r'^#[^\s]*\s', '', s) # remove leading identifier
  1435. # s = re.sub(r'\w+:', '', s) # remove role tags
  1436. # return s
  1437. ######################################################################
  1438. ## Demonstration
  1439. ######################################################################
  1440. def demo():
  1441. """
  1442. A demonstration showing how Trees and Trees can be
  1443. used. This demonstration creates a Tree, and loads a
  1444. Tree from the Treebank corpus,
  1445. and shows the results of calling several of their methods.
  1446. """
  1447. from nltk import Tree, ProbabilisticTree
  1448. # Demonstrate tree parsing.
  1449. s = '(S (NP (DT the) (NN cat)) (VP (VBD ate) (NP (DT a) (NN cookie))))'
  1450. t = Tree.fromstring(s)
  1451. print("Convert bracketed string into tree:")
  1452. print(t)
  1453. print(t.__repr__())
  1454. print("Display tree properties:")
  1455. print(t.label()) # tree's constituent type
  1456. print(t[0]) # tree's first child
  1457. print(t[1]) # tree's second child
  1458. print(t.height())
  1459. print(t.leaves())
  1460. print(t[1])
  1461. print(t[1, 1])
  1462. print(t[1, 1, 0])
  1463. # Demonstrate tree modification.
  1464. the_cat = t[0]
  1465. the_cat.insert(1, Tree.fromstring('(JJ big)'))
  1466. print("Tree modification:")
  1467. print(t)
  1468. t[1, 1, 1] = Tree.fromstring('(NN cake)')
  1469. print(t)
  1470. print()
  1471. # Tree transforms
  1472. print("Collapse unary:")
  1473. t.collapse_unary()
  1474. print(t)
  1475. print("Chomsky normal form:")
  1476. t.chomsky_normal_form()
  1477. print(t)
  1478. print()
  1479. # Demonstrate probabilistic trees.
  1480. pt = ProbabilisticTree('x', ['y', 'z'], prob=0.5)
  1481. print("Probabilistic Tree:")
  1482. print(pt)
  1483. print()
  1484. # Demonstrate parsing of treebank output format.
  1485. t = Tree.fromstring(t.pformat())
  1486. print("Convert tree to bracketed string and back again:")
  1487. print(t)
  1488. print()
  1489. # Demonstrate LaTeX output
  1490. print("LaTeX output:")
  1491. print(t.pformat_latex_qtree())
  1492. print()
  1493. # Demonstrate Productions
  1494. print("Production output:")
  1495. print(t.productions())
  1496. print()
  1497. # Demonstrate tree nodes containing objects other than strings
  1498. t.set_label(('test', 3))
  1499. print(t)
  1500. __all__ = [
  1501. 'ImmutableProbabilisticTree',
  1502. 'ImmutableTree',
  1503. 'ProbabilisticMixIn',
  1504. 'ProbabilisticTree',
  1505. 'Tree',
  1506. 'bracket_parse',
  1507. 'sinica_parse',
  1508. 'ParentedTree',
  1509. 'MultiParentedTree',
  1510. 'ImmutableParentedTree',
  1511. 'ImmutableMultiParentedTree',
  1512. ]