tgrep.py 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Natural Language Toolkit: TGrep search
  5. #
  6. # Copyright (C) 2001-2020 NLTK Project
  7. # Author: Will Roberts <wildwilhelm@gmail.com>
  8. # URL: <http://nltk.org/>
  9. # For license information, see LICENSE.TXT
  10. """
  11. ============================================
  12. TGrep search implementation for NLTK trees
  13. ============================================
  14. This module supports TGrep2 syntax for matching parts of NLTK Trees.
  15. Note that many tgrep operators require the tree passed to be a
  16. ``ParentedTree``.
  17. External links:
  18. - `Tgrep tutorial <http://www.stanford.edu/dept/linguistics/corpora/cas-tut-tgrep.html>`_
  19. - `Tgrep2 manual <http://tedlab.mit.edu/~dr/Tgrep2/tgrep2.pdf>`_
  20. - `Tgrep2 source <http://tedlab.mit.edu/~dr/Tgrep2/>`_
  21. Usage
  22. =====
  23. >>> from nltk.tree import ParentedTree
  24. >>> from nltk.tgrep import tgrep_nodes, tgrep_positions
  25. >>> tree = ParentedTree.fromstring('(S (NP (DT the) (JJ big) (NN dog)) (VP bit) (NP (DT a) (NN cat)))')
  26. >>> list(tgrep_nodes('NN', [tree]))
  27. [[ParentedTree('NN', ['dog']), ParentedTree('NN', ['cat'])]]
  28. >>> list(tgrep_positions('NN', [tree]))
  29. [[(0, 2), (2, 1)]]
  30. >>> list(tgrep_nodes('DT', [tree]))
  31. [[ParentedTree('DT', ['the']), ParentedTree('DT', ['a'])]]
  32. >>> list(tgrep_nodes('DT $ JJ', [tree]))
  33. [[ParentedTree('DT', ['the'])]]
  34. This implementation adds syntax to select nodes based on their NLTK
  35. tree position. This syntax is ``N`` plus a Python tuple representing
  36. the tree position. For instance, ``N()``, ``N(0,)``, ``N(0,0)`` are
  37. valid node selectors. Example:
  38. >>> tree = ParentedTree.fromstring('(S (NP (DT the) (JJ big) (NN dog)) (VP bit) (NP (DT a) (NN cat)))')
  39. >>> tree[0,0]
  40. ParentedTree('DT', ['the'])
  41. >>> tree[0,0].treeposition()
  42. (0, 0)
  43. >>> list(tgrep_nodes('N(0,0)', [tree]))
  44. [[ParentedTree('DT', ['the'])]]
  45. Caveats:
  46. ========
  47. - Link modifiers: "?" and "=" are not implemented.
  48. - Tgrep compatibility: Using "@" for "!", "{" for "<", "}" for ">" are
  49. not implemented.
  50. - The "=" and "~" links are not implemented.
  51. Known Issues:
  52. =============
  53. - There are some issues with link relations involving leaf nodes
  54. (which are represented as bare strings in NLTK trees). For
  55. instance, consider the tree::
  56. (S (A x))
  57. The search string ``* !>> S`` should select all nodes which are not
  58. dominated in some way by an ``S`` node (i.e., all nodes which are
  59. not descendants of an ``S``). Clearly, in this tree, the only node
  60. which fulfills this criterion is the top node (since it is not
  61. dominated by anything). However, the code here will find both the
  62. top node and the leaf node ``x``. This is because we cannot recover
  63. the parent of the leaf, since it is stored as a bare string.
  64. A possible workaround, when performing this kind of search, would be
  65. to filter out all leaf nodes.
  66. Implementation notes
  67. ====================
  68. This implementation is (somewhat awkwardly) based on lambda functions
  69. which are predicates on a node. A predicate is a function which is
  70. either True or False; using a predicate function, we can identify sets
  71. of nodes with particular properties. A predicate function, could, for
  72. instance, return True only if a particular node has a label matching a
  73. particular regular expression, and has a daughter node which has no
  74. sisters. Because tgrep2 search strings can do things statefully (such
  75. as substituting in macros, and binding nodes with node labels), the
  76. actual predicate function is declared with three arguments::
  77. pred = lambda n, m, l: return True # some logic here
  78. ``n``
  79. is a node in a tree; this argument must always be given
  80. ``m``
  81. contains a dictionary, mapping macro names onto predicate functions
  82. ``l``
  83. is a dictionary to map node labels onto nodes in the tree
  84. ``m`` and ``l`` are declared to default to ``None``, and so need not be
  85. specified in a call to a predicate. Predicates which call other
  86. predicates must always pass the value of these arguments on. The
  87. top-level predicate (constructed by ``_tgrep_exprs_action``) binds the
  88. macro definitions to ``m`` and initialises ``l`` to an empty dictionary.
  89. """
  90. import functools
  91. import re
  92. try:
  93. import pyparsing
  94. except ImportError:
  95. print("Warning: nltk.tgrep will not work without the `pyparsing` package")
  96. print("installed.")
  97. import nltk.tree
  98. class TgrepException(Exception):
  99. """Tgrep exception type."""
  100. pass
  101. def ancestors(node):
  102. """
  103. Returns the list of all nodes dominating the given tree node.
  104. This method will not work with leaf nodes, since there is no way
  105. to recover the parent.
  106. """
  107. results = []
  108. try:
  109. current = node.parent()
  110. except AttributeError:
  111. # if node is a leaf, we cannot retrieve its parent
  112. return results
  113. while current:
  114. results.append(current)
  115. current = current.parent()
  116. return results
  117. def unique_ancestors(node):
  118. """
  119. Returns the list of all nodes dominating the given node, where
  120. there is only a single path of descent.
  121. """
  122. results = []
  123. try:
  124. current = node.parent()
  125. except AttributeError:
  126. # if node is a leaf, we cannot retrieve its parent
  127. return results
  128. while current and len(current) == 1:
  129. results.append(current)
  130. current = current.parent()
  131. return results
  132. def _descendants(node):
  133. """
  134. Returns the list of all nodes which are descended from the given
  135. tree node in some way.
  136. """
  137. try:
  138. treepos = node.treepositions()
  139. except AttributeError:
  140. return []
  141. return [node[x] for x in treepos[1:]]
  142. def _leftmost_descendants(node):
  143. """
  144. Returns the set of all nodes descended in some way through
  145. left branches from this node.
  146. """
  147. try:
  148. treepos = node.treepositions()
  149. except AttributeError:
  150. return []
  151. return [node[x] for x in treepos[1:] if all(y == 0 for y in x)]
  152. def _rightmost_descendants(node):
  153. """
  154. Returns the set of all nodes descended in some way through
  155. right branches from this node.
  156. """
  157. try:
  158. rightmost_leaf = max(node.treepositions())
  159. except AttributeError:
  160. return []
  161. return [node[rightmost_leaf[:i]] for i in range(1, len(rightmost_leaf) + 1)]
  162. def _istree(obj):
  163. """Predicate to check whether `obj` is a nltk.tree.Tree."""
  164. return isinstance(obj, nltk.tree.Tree)
  165. def _unique_descendants(node):
  166. """
  167. Returns the list of all nodes descended from the given node, where
  168. there is only a single path of descent.
  169. """
  170. results = []
  171. current = node
  172. while current and _istree(current) and len(current) == 1:
  173. current = current[0]
  174. results.append(current)
  175. return results
  176. def _before(node):
  177. """
  178. Returns the set of all nodes that are before the given node.
  179. """
  180. try:
  181. pos = node.treeposition()
  182. tree = node.root()
  183. except AttributeError:
  184. return []
  185. return [tree[x] for x in tree.treepositions() if x[: len(pos)] < pos[: len(x)]]
  186. def _immediately_before(node):
  187. """
  188. Returns the set of all nodes that are immediately before the given
  189. node.
  190. Tree node A immediately precedes node B if the last terminal
  191. symbol (word) produced by A immediately precedes the first
  192. terminal symbol produced by B.
  193. """
  194. try:
  195. pos = node.treeposition()
  196. tree = node.root()
  197. except AttributeError:
  198. return []
  199. # go "upwards" from pos until there is a place we can go to the left
  200. idx = len(pos) - 1
  201. while 0 <= idx and pos[idx] == 0:
  202. idx -= 1
  203. if idx < 0:
  204. return []
  205. pos = list(pos[: idx + 1])
  206. pos[-1] -= 1
  207. before = tree[pos]
  208. return [before] + _rightmost_descendants(before)
  209. def _after(node):
  210. """
  211. Returns the set of all nodes that are after the given node.
  212. """
  213. try:
  214. pos = node.treeposition()
  215. tree = node.root()
  216. except AttributeError:
  217. return []
  218. return [tree[x] for x in tree.treepositions() if x[: len(pos)] > pos[: len(x)]]
  219. def _immediately_after(node):
  220. """
  221. Returns the set of all nodes that are immediately after the given
  222. node.
  223. Tree node A immediately follows node B if the first terminal
  224. symbol (word) produced by A immediately follows the last
  225. terminal symbol produced by B.
  226. """
  227. try:
  228. pos = node.treeposition()
  229. tree = node.root()
  230. current = node.parent()
  231. except AttributeError:
  232. return []
  233. # go "upwards" from pos until there is a place we can go to the
  234. # right
  235. idx = len(pos) - 1
  236. while 0 <= idx and pos[idx] == len(current) - 1:
  237. idx -= 1
  238. current = current.parent()
  239. if idx < 0:
  240. return []
  241. pos = list(pos[: idx + 1])
  242. pos[-1] += 1
  243. after = tree[pos]
  244. return [after] + _leftmost_descendants(after)
  245. def _tgrep_node_literal_value(node):
  246. """
  247. Gets the string value of a given parse tree node, for comparison
  248. using the tgrep node literal predicates.
  249. """
  250. return node.label() if _istree(node) else str(node)
  251. def _tgrep_macro_use_action(_s, _l, tokens):
  252. """
  253. Builds a lambda function which looks up the macro name used.
  254. """
  255. assert len(tokens) == 1
  256. assert tokens[0][0] == "@"
  257. macro_name = tokens[0][1:]
  258. def macro_use(n, m=None, l=None):
  259. if m is None or macro_name not in m:
  260. raise TgrepException("macro {0} not defined".format(macro_name))
  261. return m[macro_name](n, m, l)
  262. return macro_use
  263. def _tgrep_node_action(_s, _l, tokens):
  264. """
  265. Builds a lambda function representing a predicate on a tree node
  266. depending on the name of its node.
  267. """
  268. if tokens[0] == "'":
  269. # strip initial apostrophe (tgrep2 print command)
  270. tokens = tokens[1:]
  271. if len(tokens) > 1:
  272. # disjunctive definition of a node name
  273. assert list(set(tokens[1::2])) == ["|"]
  274. # recursively call self to interpret each node name definition
  275. tokens = [_tgrep_node_action(None, None, [node]) for node in tokens[::2]]
  276. # capture tokens and return the disjunction
  277. return (lambda t: lambda n, m=None, l=None: any(f(n, m, l) for f in t))(tokens)
  278. else:
  279. if hasattr(tokens[0], "__call__"):
  280. # this is a previously interpreted parenthetical node
  281. # definition (lambda function)
  282. return tokens[0]
  283. elif tokens[0] == "*" or tokens[0] == "__":
  284. return lambda n, m=None, l=None: True
  285. elif tokens[0].startswith('"'):
  286. assert tokens[0].endswith('"')
  287. node_lit = tokens[0][1:-1].replace('\\"', '"').replace("\\\\", "\\")
  288. return (
  289. lambda s: lambda n, m=None, l=None: _tgrep_node_literal_value(n) == s
  290. )(node_lit)
  291. elif tokens[0].startswith("/"):
  292. assert tokens[0].endswith("/")
  293. node_lit = tokens[0][1:-1]
  294. return (
  295. lambda r: lambda n, m=None, l=None: r.search(
  296. _tgrep_node_literal_value(n)
  297. )
  298. )(re.compile(node_lit))
  299. elif tokens[0].startswith("i@"):
  300. node_func = _tgrep_node_action(_s, _l, [tokens[0][2:].lower()])
  301. return (
  302. lambda f: lambda n, m=None, l=None: f(
  303. _tgrep_node_literal_value(n).lower()
  304. )
  305. )(node_func)
  306. else:
  307. return (
  308. lambda s: lambda n, m=None, l=None: _tgrep_node_literal_value(n) == s
  309. )(tokens[0])
  310. def _tgrep_parens_action(_s, _l, tokens):
  311. """
  312. Builds a lambda function representing a predicate on a tree node
  313. from a parenthetical notation.
  314. """
  315. assert len(tokens) == 3
  316. assert tokens[0] == "("
  317. assert tokens[2] == ")"
  318. return tokens[1]
  319. def _tgrep_nltk_tree_pos_action(_s, _l, tokens):
  320. """
  321. Builds a lambda function representing a predicate on a tree node
  322. which returns true if the node is located at a specific tree
  323. position.
  324. """
  325. # recover the tuple from the parsed sting
  326. node_tree_position = tuple(int(x) for x in tokens if x.isdigit())
  327. # capture the node's tree position
  328. return (
  329. lambda i: lambda n, m=None, l=None: (
  330. hasattr(n, "treeposition") and n.treeposition() == i
  331. )
  332. )(node_tree_position)
  333. def _tgrep_relation_action(_s, _l, tokens):
  334. """
  335. Builds a lambda function representing a predicate on a tree node
  336. depending on its relation to other nodes in the tree.
  337. """
  338. # process negation first if needed
  339. negated = False
  340. if tokens[0] == "!":
  341. negated = True
  342. tokens = tokens[1:]
  343. if tokens[0] == "[":
  344. # process square-bracketed relation expressions
  345. assert len(tokens) == 3
  346. assert tokens[2] == "]"
  347. retval = tokens[1]
  348. else:
  349. # process operator-node relation expressions
  350. assert len(tokens) == 2
  351. operator, predicate = tokens
  352. # A < B A is the parent of (immediately dominates) B.
  353. if operator == "<":
  354. retval = lambda n, m=None, l=None: (
  355. _istree(n) and any(predicate(x, m, l) for x in n)
  356. )
  357. # A > B A is the child of B.
  358. elif operator == ">":
  359. retval = lambda n, m=None, l=None: (
  360. hasattr(n, "parent")
  361. and bool(n.parent())
  362. and predicate(n.parent(), m, l)
  363. )
  364. # A <, B Synonymous with A <1 B.
  365. elif operator == "<," or operator == "<1":
  366. retval = lambda n, m=None, l=None: (
  367. _istree(n) and bool(list(n)) and predicate(n[0], m, l)
  368. )
  369. # A >, B Synonymous with A >1 B.
  370. elif operator == ">," or operator == ">1":
  371. retval = lambda n, m=None, l=None: (
  372. hasattr(n, "parent")
  373. and bool(n.parent())
  374. and (n is n.parent()[0])
  375. and predicate(n.parent(), m, l)
  376. )
  377. # A <N B B is the Nth child of A (the first child is <1).
  378. elif operator[0] == "<" and operator[1:].isdigit():
  379. idx = int(operator[1:])
  380. # capture the index parameter
  381. retval = (
  382. lambda i: lambda n, m=None, l=None: (
  383. _istree(n)
  384. and bool(list(n))
  385. and 0 <= i < len(n)
  386. and predicate(n[i], m, l)
  387. )
  388. )(idx - 1)
  389. # A >N B A is the Nth child of B (the first child is >1).
  390. elif operator[0] == ">" and operator[1:].isdigit():
  391. idx = int(operator[1:])
  392. # capture the index parameter
  393. retval = (
  394. lambda i: lambda n, m=None, l=None: (
  395. hasattr(n, "parent")
  396. and bool(n.parent())
  397. and 0 <= i < len(n.parent())
  398. and (n is n.parent()[i])
  399. and predicate(n.parent(), m, l)
  400. )
  401. )(idx - 1)
  402. # A <' B B is the last child of A (also synonymous with A <-1 B).
  403. # A <- B B is the last child of A (synonymous with A <-1 B).
  404. elif operator == "<'" or operator == "<-" or operator == "<-1":
  405. retval = lambda n, m=None, l=None: (
  406. _istree(n) and bool(list(n)) and predicate(n[-1], m, l)
  407. )
  408. # A >' B A is the last child of B (also synonymous with A >-1 B).
  409. # A >- B A is the last child of B (synonymous with A >-1 B).
  410. elif operator == ">'" or operator == ">-" or operator == ">-1":
  411. retval = lambda n, m=None, l=None: (
  412. hasattr(n, "parent")
  413. and bool(n.parent())
  414. and (n is n.parent()[-1])
  415. and predicate(n.parent(), m, l)
  416. )
  417. # A <-N B B is the N th-to-last child of A (the last child is <-1).
  418. elif operator[:2] == "<-" and operator[2:].isdigit():
  419. idx = -int(operator[2:])
  420. # capture the index parameter
  421. retval = (
  422. lambda i: lambda n, m=None, l=None: (
  423. _istree(n)
  424. and bool(list(n))
  425. and 0 <= (i + len(n)) < len(n)
  426. and predicate(n[i + len(n)], m, l)
  427. )
  428. )(idx)
  429. # A >-N B A is the N th-to-last child of B (the last child is >-1).
  430. elif operator[:2] == ">-" and operator[2:].isdigit():
  431. idx = -int(operator[2:])
  432. # capture the index parameter
  433. retval = (
  434. lambda i: lambda n, m=None, l=None: (
  435. hasattr(n, "parent")
  436. and bool(n.parent())
  437. and 0 <= (i + len(n.parent())) < len(n.parent())
  438. and (n is n.parent()[i + len(n.parent())])
  439. and predicate(n.parent(), m, l)
  440. )
  441. )(idx)
  442. # A <: B B is the only child of A
  443. elif operator == "<:":
  444. retval = lambda n, m=None, l=None: (
  445. _istree(n) and len(n) == 1 and predicate(n[0], m, l)
  446. )
  447. # A >: B A is the only child of B.
  448. elif operator == ">:":
  449. retval = lambda n, m=None, l=None: (
  450. hasattr(n, "parent")
  451. and bool(n.parent())
  452. and len(n.parent()) == 1
  453. and predicate(n.parent(), m, l)
  454. )
  455. # A << B A dominates B (A is an ancestor of B).
  456. elif operator == "<<":
  457. retval = lambda n, m=None, l=None: (
  458. _istree(n) and any(predicate(x, m, l) for x in _descendants(n))
  459. )
  460. # A >> B A is dominated by B (A is a descendant of B).
  461. elif operator == ">>":
  462. retval = lambda n, m=None, l=None: any(
  463. predicate(x, m, l) for x in ancestors(n)
  464. )
  465. # A <<, B B is a left-most descendant of A.
  466. elif operator == "<<," or operator == "<<1":
  467. retval = lambda n, m=None, l=None: (
  468. _istree(n) and any(predicate(x, m, l) for x in _leftmost_descendants(n))
  469. )
  470. # A >>, B A is a left-most descendant of B.
  471. elif operator == ">>,":
  472. retval = lambda n, m=None, l=None: any(
  473. (predicate(x, m, l) and n in _leftmost_descendants(x))
  474. for x in ancestors(n)
  475. )
  476. # A <<' B B is a right-most descendant of A.
  477. elif operator == "<<'":
  478. retval = lambda n, m=None, l=None: (
  479. _istree(n)
  480. and any(predicate(x, m, l) for x in _rightmost_descendants(n))
  481. )
  482. # A >>' B A is a right-most descendant of B.
  483. elif operator == ">>'":
  484. retval = lambda n, m=None, l=None: any(
  485. (predicate(x, m, l) and n in _rightmost_descendants(x))
  486. for x in ancestors(n)
  487. )
  488. # A <<: B There is a single path of descent from A and B is on it.
  489. elif operator == "<<:":
  490. retval = lambda n, m=None, l=None: (
  491. _istree(n) and any(predicate(x, m, l) for x in _unique_descendants(n))
  492. )
  493. # A >>: B There is a single path of descent from B and A is on it.
  494. elif operator == ">>:":
  495. retval = lambda n, m=None, l=None: any(
  496. predicate(x, m, l) for x in unique_ancestors(n)
  497. )
  498. # A . B A immediately precedes B.
  499. elif operator == ".":
  500. retval = lambda n, m=None, l=None: any(
  501. predicate(x, m, l) for x in _immediately_after(n)
  502. )
  503. # A , B A immediately follows B.
  504. elif operator == ",":
  505. retval = lambda n, m=None, l=None: any(
  506. predicate(x, m, l) for x in _immediately_before(n)
  507. )
  508. # A .. B A precedes B.
  509. elif operator == "..":
  510. retval = lambda n, m=None, l=None: any(
  511. predicate(x, m, l) for x in _after(n)
  512. )
  513. # A ,, B A follows B.
  514. elif operator == ",,":
  515. retval = lambda n, m=None, l=None: any(
  516. predicate(x, m, l) for x in _before(n)
  517. )
  518. # A $ B A is a sister of B (and A != B).
  519. elif operator == "$" or operator == "%":
  520. retval = lambda n, m=None, l=None: (
  521. hasattr(n, "parent")
  522. and bool(n.parent())
  523. and any(predicate(x, m, l) for x in n.parent() if x is not n)
  524. )
  525. # A $. B A is a sister of and immediately precedes B.
  526. elif operator == "$." or operator == "%.":
  527. retval = lambda n, m=None, l=None: (
  528. hasattr(n, "right_sibling")
  529. and bool(n.right_sibling())
  530. and predicate(n.right_sibling(), m, l)
  531. )
  532. # A $, B A is a sister of and immediately follows B.
  533. elif operator == "$," or operator == "%,":
  534. retval = lambda n, m=None, l=None: (
  535. hasattr(n, "left_sibling")
  536. and bool(n.left_sibling())
  537. and predicate(n.left_sibling(), m, l)
  538. )
  539. # A $.. B A is a sister of and precedes B.
  540. elif operator == "$.." or operator == "%..":
  541. retval = lambda n, m=None, l=None: (
  542. hasattr(n, "parent")
  543. and hasattr(n, "parent_index")
  544. and bool(n.parent())
  545. and any(predicate(x, m, l) for x in n.parent()[n.parent_index() + 1 :])
  546. )
  547. # A $,, B A is a sister of and follows B.
  548. elif operator == "$,," or operator == "%,,":
  549. retval = lambda n, m=None, l=None: (
  550. hasattr(n, "parent")
  551. and hasattr(n, "parent_index")
  552. and bool(n.parent())
  553. and any(predicate(x, m, l) for x in n.parent()[: n.parent_index()])
  554. )
  555. else:
  556. raise TgrepException(
  557. 'cannot interpret tgrep operator "{0}"'.format(operator)
  558. )
  559. # now return the built function
  560. if negated:
  561. return (lambda r: (lambda n, m=None, l=None: not r(n, m, l)))(retval)
  562. else:
  563. return retval
  564. def _tgrep_conjunction_action(_s, _l, tokens, join_char="&"):
  565. """
  566. Builds a lambda function representing a predicate on a tree node
  567. from the conjunction of several other such lambda functions.
  568. This is prototypically called for expressions like
  569. (`tgrep_rel_conjunction`)::
  570. < NP & < AP < VP
  571. where tokens is a list of predicates representing the relations
  572. (`< NP`, `< AP`, and `< VP`), possibly with the character `&`
  573. included (as in the example here).
  574. This is also called for expressions like (`tgrep_node_expr2`)::
  575. NP < NN
  576. S=s < /NP/=n : s < /VP/=v : n .. v
  577. tokens[0] is a tgrep_expr predicate; tokens[1:] are an (optional)
  578. list of segmented patterns (`tgrep_expr_labeled`, processed by
  579. `_tgrep_segmented_pattern_action`).
  580. """
  581. # filter out the ampersand
  582. tokens = [x for x in tokens if x != join_char]
  583. if len(tokens) == 1:
  584. return tokens[0]
  585. else:
  586. return (
  587. lambda ts: lambda n, m=None, l=None: all(
  588. predicate(n, m, l) for predicate in ts
  589. )
  590. )(tokens)
  591. def _tgrep_segmented_pattern_action(_s, _l, tokens):
  592. """
  593. Builds a lambda function representing a segmented pattern.
  594. Called for expressions like (`tgrep_expr_labeled`)::
  595. =s .. =v < =n
  596. This is a segmented pattern, a tgrep2 expression which begins with
  597. a node label.
  598. The problem is that for segemented_pattern_action (': =v < =s'),
  599. the first element (in this case, =v) is specifically selected by
  600. virtue of matching a particular node in the tree; to retrieve
  601. the node, we need the label, not a lambda function. For node
  602. labels inside a tgrep_node_expr, we need a lambda function which
  603. returns true if the node visited is the same as =v.
  604. We solve this by creating two copies of a node_label_use in the
  605. grammar; the label use inside a tgrep_expr_labeled has a separate
  606. parse action to the pred use inside a node_expr. See
  607. `_tgrep_node_label_use_action` and
  608. `_tgrep_node_label_pred_use_action`.
  609. """
  610. # tokens[0] is a string containing the node label
  611. node_label = tokens[0]
  612. # tokens[1:] is an (optional) list of predicates which must all
  613. # hold of the bound node
  614. reln_preds = tokens[1:]
  615. def pattern_segment_pred(n, m=None, l=None):
  616. """This predicate function ignores its node argument."""
  617. # look up the bound node using its label
  618. if l is None or node_label not in l:
  619. raise TgrepException(
  620. "node_label ={0} not bound in pattern".format(node_label)
  621. )
  622. node = l[node_label]
  623. # match the relation predicates against the node
  624. return all(pred(node, m, l) for pred in reln_preds)
  625. return pattern_segment_pred
  626. def _tgrep_node_label_use_action(_s, _l, tokens):
  627. """
  628. Returns the node label used to begin a tgrep_expr_labeled. See
  629. `_tgrep_segmented_pattern_action`.
  630. Called for expressions like (`tgrep_node_label_use`)::
  631. =s
  632. when they appear as the first element of a `tgrep_expr_labeled`
  633. expression (see `_tgrep_segmented_pattern_action`).
  634. It returns the node label.
  635. """
  636. assert len(tokens) == 1
  637. assert tokens[0].startswith("=")
  638. return tokens[0][1:]
  639. def _tgrep_node_label_pred_use_action(_s, _l, tokens):
  640. """
  641. Builds a lambda function representing a predicate on a tree node
  642. which describes the use of a previously bound node label.
  643. Called for expressions like (`tgrep_node_label_use_pred`)::
  644. =s
  645. when they appear inside a tgrep_node_expr (for example, inside a
  646. relation). The predicate returns true if and only if its node
  647. argument is identical the the node looked up in the node label
  648. dictionary using the node's label.
  649. """
  650. assert len(tokens) == 1
  651. assert tokens[0].startswith("=")
  652. node_label = tokens[0][1:]
  653. def node_label_use_pred(n, m=None, l=None):
  654. # look up the bound node using its label
  655. if l is None or node_label not in l:
  656. raise TgrepException(
  657. "node_label ={0} not bound in pattern".format(node_label)
  658. )
  659. node = l[node_label]
  660. # truth means the given node is this node
  661. return n is node
  662. return node_label_use_pred
  663. def _tgrep_bind_node_label_action(_s, _l, tokens):
  664. """
  665. Builds a lambda function representing a predicate on a tree node
  666. which can optionally bind a matching node into the tgrep2 string's
  667. label_dict.
  668. Called for expressions like (`tgrep_node_expr2`)::
  669. /NP/
  670. @NP=n
  671. """
  672. # tokens[0] is a tgrep_node_expr
  673. if len(tokens) == 1:
  674. return tokens[0]
  675. else:
  676. # if present, tokens[1] is the character '=', and tokens[2] is
  677. # a tgrep_node_label, a string value containing the node label
  678. assert len(tokens) == 3
  679. assert tokens[1] == "="
  680. node_pred = tokens[0]
  681. node_label = tokens[2]
  682. def node_label_bind_pred(n, m=None, l=None):
  683. if node_pred(n, m, l):
  684. # bind `n` into the dictionary `l`
  685. if l is None:
  686. raise TgrepException(
  687. "cannot bind node_label {0}: label_dict is None".format(
  688. node_label
  689. )
  690. )
  691. l[node_label] = n
  692. return True
  693. else:
  694. return False
  695. return node_label_bind_pred
  696. def _tgrep_rel_disjunction_action(_s, _l, tokens):
  697. """
  698. Builds a lambda function representing a predicate on a tree node
  699. from the disjunction of several other such lambda functions.
  700. """
  701. # filter out the pipe
  702. tokens = [x for x in tokens if x != "|"]
  703. if len(tokens) == 1:
  704. return tokens[0]
  705. elif len(tokens) == 2:
  706. return (lambda a, b: lambda n, m=None, l=None: a(n, m, l) or b(n, m, l))(
  707. tokens[0], tokens[1]
  708. )
  709. def _macro_defn_action(_s, _l, tokens):
  710. """
  711. Builds a dictionary structure which defines the given macro.
  712. """
  713. assert len(tokens) == 3
  714. assert tokens[0] == "@"
  715. return {tokens[1]: tokens[2]}
  716. def _tgrep_exprs_action(_s, _l, tokens):
  717. """
  718. This is the top-lebel node in a tgrep2 search string; the
  719. predicate function it returns binds together all the state of a
  720. tgrep2 search string.
  721. Builds a lambda function representing a predicate on a tree node
  722. from the disjunction of several tgrep expressions. Also handles
  723. macro definitions and macro name binding, and node label
  724. definitions and node label binding.
  725. """
  726. if len(tokens) == 1:
  727. return lambda n, m=None, l=None: tokens[0](n, None, {})
  728. # filter out all the semicolons
  729. tokens = [x for x in tokens if x != ";"]
  730. # collect all macro definitions
  731. macro_dict = {}
  732. macro_defs = [tok for tok in tokens if isinstance(tok, dict)]
  733. for macro_def in macro_defs:
  734. macro_dict.update(macro_def)
  735. # collect all tgrep expressions
  736. tgrep_exprs = [tok for tok in tokens if not isinstance(tok, dict)]
  737. # create a new scope for the node label dictionary
  738. def top_level_pred(n, m=macro_dict, l=None):
  739. label_dict = {}
  740. # bind macro definitions and OR together all tgrep_exprs
  741. return any(predicate(n, m, label_dict) for predicate in tgrep_exprs)
  742. return top_level_pred
  743. def _build_tgrep_parser(set_parse_actions=True):
  744. """
  745. Builds a pyparsing-based parser object for tokenizing and
  746. interpreting tgrep search strings.
  747. """
  748. tgrep_op = pyparsing.Optional("!") + pyparsing.Regex("[$%,.<>][%,.<>0-9-':]*")
  749. tgrep_qstring = pyparsing.QuotedString(
  750. quoteChar='"', escChar="\\", unquoteResults=False
  751. )
  752. tgrep_node_regex = pyparsing.QuotedString(
  753. quoteChar="/", escChar="\\", unquoteResults=False
  754. )
  755. tgrep_qstring_icase = pyparsing.Regex('i@\\"(?:[^"\\n\\r\\\\]|(?:\\\\.))*\\"')
  756. tgrep_node_regex_icase = pyparsing.Regex("i@\\/(?:[^/\\n\\r\\\\]|(?:\\\\.))*\\/")
  757. tgrep_node_literal = pyparsing.Regex("[^][ \r\t\n;:.,&|<>()$!@%'^=]+")
  758. tgrep_expr = pyparsing.Forward()
  759. tgrep_relations = pyparsing.Forward()
  760. tgrep_parens = pyparsing.Literal("(") + tgrep_expr + ")"
  761. tgrep_nltk_tree_pos = (
  762. pyparsing.Literal("N(")
  763. + pyparsing.Optional(
  764. pyparsing.Word(pyparsing.nums)
  765. + ","
  766. + pyparsing.Optional(
  767. pyparsing.delimitedList(pyparsing.Word(pyparsing.nums), delim=",")
  768. + pyparsing.Optional(",")
  769. )
  770. )
  771. + ")"
  772. )
  773. tgrep_node_label = pyparsing.Regex("[A-Za-z0-9]+")
  774. tgrep_node_label_use = pyparsing.Combine("=" + tgrep_node_label)
  775. # see _tgrep_segmented_pattern_action
  776. tgrep_node_label_use_pred = tgrep_node_label_use.copy()
  777. macro_name = pyparsing.Regex("[^];:.,&|<>()[$!@%'^=\r\t\n ]+")
  778. macro_name.setWhitespaceChars("")
  779. macro_use = pyparsing.Combine("@" + macro_name)
  780. tgrep_node_expr = (
  781. tgrep_node_label_use_pred
  782. | macro_use
  783. | tgrep_nltk_tree_pos
  784. | tgrep_qstring_icase
  785. | tgrep_node_regex_icase
  786. | tgrep_qstring
  787. | tgrep_node_regex
  788. | "*"
  789. | tgrep_node_literal
  790. )
  791. tgrep_node_expr2 = (
  792. tgrep_node_expr
  793. + pyparsing.Literal("=").setWhitespaceChars("")
  794. + tgrep_node_label.copy().setWhitespaceChars("")
  795. ) | tgrep_node_expr
  796. tgrep_node = tgrep_parens | (
  797. pyparsing.Optional("'")
  798. + tgrep_node_expr2
  799. + pyparsing.ZeroOrMore("|" + tgrep_node_expr)
  800. )
  801. tgrep_brackets = pyparsing.Optional("!") + "[" + tgrep_relations + "]"
  802. tgrep_relation = tgrep_brackets | (tgrep_op + tgrep_node)
  803. tgrep_rel_conjunction = pyparsing.Forward()
  804. tgrep_rel_conjunction << (
  805. tgrep_relation
  806. + pyparsing.ZeroOrMore(pyparsing.Optional("&") + tgrep_rel_conjunction)
  807. )
  808. tgrep_relations << tgrep_rel_conjunction + pyparsing.ZeroOrMore(
  809. "|" + tgrep_relations
  810. )
  811. tgrep_expr << tgrep_node + pyparsing.Optional(tgrep_relations)
  812. tgrep_expr_labeled = tgrep_node_label_use + pyparsing.Optional(tgrep_relations)
  813. tgrep_expr2 = tgrep_expr + pyparsing.ZeroOrMore(":" + tgrep_expr_labeled)
  814. macro_defn = (
  815. pyparsing.Literal("@") + pyparsing.White().suppress() + macro_name + tgrep_expr2
  816. )
  817. tgrep_exprs = (
  818. pyparsing.Optional(macro_defn + pyparsing.ZeroOrMore(";" + macro_defn) + ";")
  819. + tgrep_expr2
  820. + pyparsing.ZeroOrMore(";" + (macro_defn | tgrep_expr2))
  821. + pyparsing.ZeroOrMore(";").suppress()
  822. )
  823. if set_parse_actions:
  824. tgrep_node_label_use.setParseAction(_tgrep_node_label_use_action)
  825. tgrep_node_label_use_pred.setParseAction(_tgrep_node_label_pred_use_action)
  826. macro_use.setParseAction(_tgrep_macro_use_action)
  827. tgrep_node.setParseAction(_tgrep_node_action)
  828. tgrep_node_expr2.setParseAction(_tgrep_bind_node_label_action)
  829. tgrep_parens.setParseAction(_tgrep_parens_action)
  830. tgrep_nltk_tree_pos.setParseAction(_tgrep_nltk_tree_pos_action)
  831. tgrep_relation.setParseAction(_tgrep_relation_action)
  832. tgrep_rel_conjunction.setParseAction(_tgrep_conjunction_action)
  833. tgrep_relations.setParseAction(_tgrep_rel_disjunction_action)
  834. macro_defn.setParseAction(_macro_defn_action)
  835. # the whole expression is also the conjunction of two
  836. # predicates: the first node predicate, and the remaining
  837. # relation predicates
  838. tgrep_expr.setParseAction(_tgrep_conjunction_action)
  839. tgrep_expr_labeled.setParseAction(_tgrep_segmented_pattern_action)
  840. tgrep_expr2.setParseAction(
  841. functools.partial(_tgrep_conjunction_action, join_char=":")
  842. )
  843. tgrep_exprs.setParseAction(_tgrep_exprs_action)
  844. return tgrep_exprs.ignore("#" + pyparsing.restOfLine)
  845. def tgrep_tokenize(tgrep_string):
  846. """
  847. Tokenizes a TGrep search string into separate tokens.
  848. """
  849. parser = _build_tgrep_parser(False)
  850. if isinstance(tgrep_string, bytes):
  851. tgrep_string = tgrep_string.decode()
  852. return list(parser.parseString(tgrep_string))
  853. def tgrep_compile(tgrep_string):
  854. """
  855. Parses (and tokenizes, if necessary) a TGrep search string into a
  856. lambda function.
  857. """
  858. parser = _build_tgrep_parser(True)
  859. if isinstance(tgrep_string, bytes):
  860. tgrep_string = tgrep_string.decode()
  861. return list(parser.parseString(tgrep_string, parseAll=True))[0]
  862. def treepositions_no_leaves(tree):
  863. """
  864. Returns all the tree positions in the given tree which are not
  865. leaf nodes.
  866. """
  867. treepositions = tree.treepositions()
  868. # leaves are treeposition tuples that are not prefixes of any
  869. # other treeposition
  870. prefixes = set()
  871. for pos in treepositions:
  872. for length in range(len(pos)):
  873. prefixes.add(pos[:length])
  874. return [pos for pos in treepositions if pos in prefixes]
  875. def tgrep_positions(pattern, trees, search_leaves=True):
  876. """
  877. Return the tree positions in the trees which match the given pattern.
  878. :param pattern: a tgrep search pattern
  879. :type pattern: str or output of tgrep_compile()
  880. :param trees: a sequence of NLTK trees (usually ParentedTrees)
  881. :type trees: iter(ParentedTree) or iter(Tree)
  882. :param search_leaves: whether ot return matching leaf nodes
  883. :type search_leaves: bool
  884. :rtype: iter(tree positions)
  885. """
  886. if isinstance(pattern, (bytes, str)):
  887. pattern = tgrep_compile(pattern)
  888. for tree in trees:
  889. try:
  890. if search_leaves:
  891. positions = tree.treepositions()
  892. else:
  893. positions = treepositions_no_leaves(tree)
  894. yield [position for position in positions if pattern(tree[position])]
  895. except AttributeError:
  896. yield []
  897. def tgrep_nodes(pattern, trees, search_leaves=True):
  898. """
  899. Return the tree nodes in the trees which match the given pattern.
  900. :param pattern: a tgrep search pattern
  901. :type pattern: str or output of tgrep_compile()
  902. :param trees: a sequence of NLTK trees (usually ParentedTrees)
  903. :type trees: iter(ParentedTree) or iter(Tree)
  904. :param search_leaves: whether ot return matching leaf nodes
  905. :type search_leaves: bool
  906. :rtype: iter(tree nodes)
  907. """
  908. if isinstance(pattern, (bytes, str)):
  909. pattern = tgrep_compile(pattern)
  910. for tree in trees:
  911. try:
  912. if search_leaves:
  913. positions = tree.treepositions()
  914. else:
  915. positions = treepositions_no_leaves(tree)
  916. yield [tree[position] for position in positions if pattern(tree[position])]
  917. except AttributeError:
  918. yield []