tree.py 65 KB

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