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

1055 lines
36 KiB

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