PageRenderTime 62ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/nltk/tree.py

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