tree.py 65 KB

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