PageRenderTime 56ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/nltk/chunk/regexp.py

https://github.com/BrucePHill/nltk
Python | 1384 lines | 1139 code | 39 blank | 206 comment | 45 complexity | 948dc5daa3ff794374f760cccae91ed2 MD5 | raw file
Possible License(s): Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. # Natural Language Toolkit: Regular Expression Chunkers
  2. #
  3. # Copyright (C) 2001-2013 NLTK Project
  4. # Author: Edward Loper <edloper@gradient.cis.upenn.edu>
  5. # Steven Bird <stevenbird1@gmail.com> (minor additions)
  6. # URL: <http://www.nltk.org/>
  7. # For license information, see LICENSE.TXT
  8. from __future__ import print_function, unicode_literals
  9. from __future__ import division
  10. import re
  11. from nltk.tree import Tree
  12. from nltk.chunk.api import ChunkParserI
  13. from nltk.compat import python_2_unicode_compatible, string_types, unicode_repr
  14. ##//////////////////////////////////////////////////////
  15. ## ChunkString
  16. ##//////////////////////////////////////////////////////
  17. @python_2_unicode_compatible
  18. class ChunkString(object):
  19. """
  20. A string-based encoding of a particular chunking of a text.
  21. Internally, the ``ChunkString`` class uses a single string to
  22. encode the chunking of the input text. This string contains a
  23. sequence of angle-bracket delimited tags, with chunking indicated
  24. by braces. An example of this encoding is::
  25. {<DT><JJ><NN>}<VBN><IN>{<DT><NN>}<.>{<DT><NN>}<VBD><.>
  26. ``ChunkString`` are created from tagged texts (i.e., lists of
  27. ``tokens`` whose type is ``TaggedType``). Initially, nothing is
  28. chunked.
  29. The chunking of a ``ChunkString`` can be modified with the ``xform()``
  30. method, which uses a regular expression to transform the string
  31. representation. These transformations should only add and remove
  32. braces; they should *not* modify the sequence of angle-bracket
  33. delimited tags.
  34. :type _str: str
  35. :ivar _str: The internal string representation of the text's
  36. encoding. This string representation contains a sequence of
  37. angle-bracket delimited tags, with chunking indicated by
  38. braces. An example of this encoding is::
  39. {<DT><JJ><NN>}<VBN><IN>{<DT><NN>}<.>{<DT><NN>}<VBD><.>
  40. :type _pieces: list(tagged tokens and chunks)
  41. :ivar _pieces: The tagged tokens and chunks encoded by this ``ChunkString``.
  42. :ivar _debug: The debug level. See the constructor docs.
  43. :cvar IN_CHUNK_PATTERN: A zero-width regexp pattern string that
  44. will only match positions that are in chunks.
  45. :cvar IN_CHINK_PATTERN: A zero-width regexp pattern string that
  46. will only match positions that are in chinks.
  47. """
  48. CHUNK_TAG_CHAR = r'[^\{\}<>]'
  49. CHUNK_TAG = r'(<%s+?>)' % CHUNK_TAG_CHAR
  50. IN_CHUNK_PATTERN = r'(?=[^\{]*\})'
  51. IN_CHINK_PATTERN = r'(?=[^\}]*(\{|$))'
  52. # These are used by _verify
  53. _CHUNK = r'(\{%s+?\})+?' % CHUNK_TAG
  54. _CHINK = r'(%s+?)+?' % CHUNK_TAG
  55. _VALID = re.compile(r'^(\{?%s\}?)*?$' % CHUNK_TAG)
  56. _BRACKETS = re.compile('[^\{\}]+')
  57. _BALANCED_BRACKETS = re.compile(r'(\{\})*$')
  58. def __init__(self, chunk_struct, debug_level=1):
  59. """
  60. Construct a new ``ChunkString`` that encodes the chunking of
  61. the text ``tagged_tokens``.
  62. :type chunk_struct: Tree
  63. :param chunk_struct: The chunk structure to be further chunked.
  64. :type debug_level: int
  65. :param debug_level: The level of debugging which should be
  66. applied to transformations on the ``ChunkString``. The
  67. valid levels are:
  68. - 0: no checks
  69. - 1: full check on to_chunkstruct
  70. - 2: full check on to_chunkstruct and cursory check after
  71. each transformation.
  72. - 3: full check on to_chunkstruct and full check after
  73. each transformation.
  74. We recommend you use at least level 1. You should
  75. probably use level 3 if you use any non-standard
  76. subclasses of ``RegexpChunkRule``.
  77. """
  78. self._top_node = chunk_struct.node
  79. self._pieces = chunk_struct[:]
  80. tags = [self._tag(tok) for tok in self._pieces]
  81. self._str = '<' + '><'.join(tags) + '>'
  82. self._debug = debug_level
  83. def _tag(self, tok):
  84. if isinstance(tok, tuple):
  85. return tok[1]
  86. elif isinstance(tok, Tree):
  87. return tok.node
  88. else:
  89. raise ValueError('chunk structures must contain tagged '
  90. 'tokens or trees')
  91. def _verify(self, s, verify_tags):
  92. """
  93. Check to make sure that ``s`` still corresponds to some chunked
  94. version of ``_pieces``.
  95. :type verify_tags: bool
  96. :param verify_tags: Whether the individual tags should be
  97. checked. If this is false, ``_verify`` will check to make
  98. sure that ``_str`` encodes a chunked version of *some*
  99. list of tokens. If this is true, then ``_verify`` will
  100. check to make sure that the tags in ``_str`` match those in
  101. ``_pieces``.
  102. :raise ValueError: if the internal string representation of
  103. this ``ChunkString`` is invalid or not consistent with _pieces.
  104. """
  105. # Check overall form
  106. if not ChunkString._VALID.match(s):
  107. raise ValueError('Transformation generated invalid '
  108. 'chunkstring:\n %s' % s)
  109. # Check that parens are balanced. If the string is long, we
  110. # have to do this in pieces, to avoid a maximum recursion
  111. # depth limit for regular expressions.
  112. brackets = ChunkString._BRACKETS.sub('', s)
  113. for i in range(1 + len(brackets) // 5000):
  114. substr = brackets[i*5000:i*5000+5000]
  115. if not ChunkString._BALANCED_BRACKETS.match(substr):
  116. raise ValueError('Transformation generated invalid '
  117. 'chunkstring:\n %s' % s)
  118. if verify_tags<=0: return
  119. tags1 = (re.split(r'[\{\}<>]+', s))[1:-1]
  120. tags2 = [self._tag(piece) for piece in self._pieces]
  121. if tags1 != tags2:
  122. raise ValueError('Transformation generated invalid '
  123. 'chunkstring: tag changed')
  124. def to_chunkstruct(self, chunk_node='CHUNK'):
  125. """
  126. Return the chunk structure encoded by this ``ChunkString``.
  127. :rtype: Tree
  128. :raise ValueError: If a transformation has generated an
  129. invalid chunkstring.
  130. """
  131. if self._debug > 0: self._verify(self._str, 1)
  132. # Use this alternating list to create the chunkstruct.
  133. pieces = []
  134. index = 0
  135. piece_in_chunk = 0
  136. for piece in re.split('[{}]', self._str):
  137. # Find the list of tokens contained in this piece.
  138. length = piece.count('<')
  139. subsequence = self._pieces[index:index+length]
  140. # Add this list of tokens to our pieces.
  141. if piece_in_chunk:
  142. pieces.append(Tree(chunk_node, subsequence))
  143. else:
  144. pieces += subsequence
  145. # Update index, piece_in_chunk
  146. index += length
  147. piece_in_chunk = not piece_in_chunk
  148. return Tree(self._top_node, pieces)
  149. def xform(self, regexp, repl):
  150. """
  151. Apply the given transformation to the string encoding of this
  152. ``ChunkString``. In particular, find all occurrences that match
  153. ``regexp``, and replace them using ``repl`` (as done by
  154. ``re.sub``).
  155. This transformation should only add and remove braces; it
  156. should *not* modify the sequence of angle-bracket delimited
  157. tags. Furthermore, this transformation may not result in
  158. improper bracketing. Note, in particular, that bracketing may
  159. not be nested.
  160. :type regexp: str or regexp
  161. :param regexp: A regular expression matching the substring
  162. that should be replaced. This will typically include a
  163. named group, which can be used by ``repl``.
  164. :type repl: str
  165. :param repl: An expression specifying what should replace the
  166. matched substring. Typically, this will include a named
  167. replacement group, specified by ``regexp``.
  168. :rtype: None
  169. :raise ValueError: If this transformation generated an
  170. invalid chunkstring.
  171. """
  172. # Do the actual substitution
  173. s = re.sub(regexp, repl, self._str)
  174. # The substitution might have generated "empty chunks"
  175. # (substrings of the form "{}"). Remove them, so they don't
  176. # interfere with other transformations.
  177. s = re.sub('\{\}', '', s)
  178. # Make sure that the transformation was legal.
  179. if self._debug > 1: self._verify(s, self._debug-2)
  180. # Commit the transformation.
  181. self._str = s
  182. def __repr__(self):
  183. """
  184. Return a string representation of this ``ChunkString``.
  185. It has the form::
  186. <ChunkString: '{<DT><JJ><NN>}<VBN><IN>{<DT><NN>}'>
  187. :rtype: str
  188. """
  189. return '<ChunkString: %s>' % unicode_repr(self._str)
  190. def __str__(self):
  191. """
  192. Return a formatted representation of this ``ChunkString``.
  193. This representation will include extra spaces to ensure that
  194. tags will line up with the representation of other
  195. ``ChunkStrings`` for the same text, regardless of the chunking.
  196. :rtype: str
  197. """
  198. # Add spaces to make everything line up.
  199. str = re.sub(r'>(?!\})', r'> ', self._str)
  200. str = re.sub(r'([^\{])<', r'\1 <', str)
  201. if str[0] == '<': str = ' ' + str
  202. return str
  203. ##//////////////////////////////////////////////////////
  204. ## Chunking Rules
  205. ##//////////////////////////////////////////////////////
  206. @python_2_unicode_compatible
  207. class RegexpChunkRule(object):
  208. """
  209. A rule specifying how to modify the chunking in a ``ChunkString``,
  210. using a transformational regular expression. The
  211. ``RegexpChunkRule`` class itself can be used to implement any
  212. transformational rule based on regular expressions. There are
  213. also a number of subclasses, which can be used to implement
  214. simpler types of rules, based on matching regular expressions.
  215. Each ``RegexpChunkRule`` has a regular expression and a
  216. replacement expression. When a ``RegexpChunkRule`` is "applied"
  217. to a ``ChunkString``, it searches the ``ChunkString`` for any
  218. substring that matches the regular expression, and replaces it
  219. using the replacement expression. This search/replace operation
  220. has the same semantics as ``re.sub``.
  221. Each ``RegexpChunkRule`` also has a description string, which
  222. gives a short (typically less than 75 characters) description of
  223. the purpose of the rule.
  224. This transformation defined by this ``RegexpChunkRule`` should
  225. only add and remove braces; it should *not* modify the sequence
  226. of angle-bracket delimited tags. Furthermore, this transformation
  227. may not result in nested or mismatched bracketing.
  228. """
  229. def __init__(self, regexp, repl, descr):
  230. """
  231. Construct a new RegexpChunkRule.
  232. :type regexp: regexp or str
  233. :param regexp: The regular expression for this ``RegexpChunkRule``.
  234. When this rule is applied to a ``ChunkString``, any
  235. substring that matches ``regexp`` will be replaced using
  236. the replacement string ``repl``. Note that this must be a
  237. normal regular expression, not a tag pattern.
  238. :type repl: str
  239. :param repl: The replacement expression for this ``RegexpChunkRule``.
  240. When this rule is applied to a ``ChunkString``, any substring
  241. that matches ``regexp`` will be replaced using ``repl``.
  242. :type descr: str
  243. :param descr: A short description of the purpose and/or effect
  244. of this rule.
  245. """
  246. if isinstance(regexp, string_types):
  247. regexp = re.compile(regexp)
  248. self._repl = repl
  249. self._descr = descr
  250. self._regexp = regexp
  251. def apply(self, chunkstr):
  252. # Keep docstring generic so we can inherit it.
  253. """
  254. Apply this rule to the given ``ChunkString``. See the
  255. class reference documentation for a description of what it
  256. means to apply a rule.
  257. :type chunkstr: ChunkString
  258. :param chunkstr: The chunkstring to which this rule is applied.
  259. :rtype: None
  260. :raise ValueError: If this transformation generated an
  261. invalid chunkstring.
  262. """
  263. chunkstr.xform(self._regexp, self._repl)
  264. def descr(self):
  265. """
  266. Return a short description of the purpose and/or effect of
  267. this rule.
  268. :rtype: str
  269. """
  270. return self._descr
  271. def __repr__(self):
  272. """
  273. Return a string representation of this rule. It has the form::
  274. <RegexpChunkRule: '{<IN|VB.*>}'->'<IN>'>
  275. Note that this representation does not include the
  276. description string; that string can be accessed
  277. separately with the ``descr()`` method.
  278. :rtype: str
  279. """
  280. return ('<RegexpChunkRule: '+unicode_repr(self._regexp.pattern)+
  281. '->'+unicode_repr(self._repl)+'>')
  282. @staticmethod
  283. def parse(s):
  284. """
  285. Create a RegexpChunkRule from a string description.
  286. Currently, the following formats are supported::
  287. {regexp} # chunk rule
  288. }regexp{ # chink rule
  289. regexp}{regexp # split rule
  290. regexp{}regexp # merge rule
  291. Where ``regexp`` is a regular expression for the rule. Any
  292. text following the comment marker (``#``) will be used as
  293. the rule's description:
  294. >>> from nltk.chunk.regexp import RegexpChunkRule
  295. >>> RegexpChunkRule.parse('{<DT>?<NN.*>+}')
  296. <ChunkRule: '<DT>?<NN.*>+'>
  297. """
  298. # Split off the comment (but don't split on '\#')
  299. m = re.match(r'(?P<rule>(\\.|[^#])*)(?P<comment>#.*)?', s)
  300. rule = m.group('rule').strip()
  301. comment = (m.group('comment') or '')[1:].strip()
  302. # Pattern bodies: chunk, chink, split, merge
  303. try:
  304. if not rule:
  305. raise ValueError('Empty chunk pattern')
  306. if rule[0] == '{' and rule[-1] == '}':
  307. return ChunkRule(rule[1:-1], comment)
  308. elif rule[0] == '}' and rule[-1] == '{':
  309. return ChinkRule(rule[1:-1], comment)
  310. elif '}{' in rule:
  311. left, right = rule.split('}{')
  312. return SplitRule(left, right, comment)
  313. elif '{}' in rule:
  314. left, right = rule.split('{}')
  315. return MergeRule(left, right, comment)
  316. elif re.match('[^{}]*{[^{}]*}[^{}]*', rule):
  317. left, chunk, right = re.split('[{}]', rule)
  318. return ChunkRuleWithContext(left, chunk, right, comment)
  319. else:
  320. raise ValueError('Illegal chunk pattern: %s' % rule)
  321. except (ValueError, re.error):
  322. raise ValueError('Illegal chunk pattern: %s' % rule)
  323. @python_2_unicode_compatible
  324. class ChunkRule(RegexpChunkRule):
  325. """
  326. A rule specifying how to add chunks to a ``ChunkString``, using a
  327. matching tag pattern. When applied to a ``ChunkString``, it will
  328. find any substring that matches this tag pattern and that is not
  329. already part of a chunk, and create a new chunk containing that
  330. substring.
  331. """
  332. def __init__(self, tag_pattern, descr):
  333. """
  334. Construct a new ``ChunkRule``.
  335. :type tag_pattern: str
  336. :param tag_pattern: This rule's tag pattern. When
  337. applied to a ``ChunkString``, this rule will
  338. chunk any substring that matches this tag pattern and that
  339. is not already part of a chunk.
  340. :type descr: str
  341. :param descr: A short description of the purpose and/or effect
  342. of this rule.
  343. """
  344. self._pattern = tag_pattern
  345. regexp = re.compile('(?P<chunk>%s)%s' %
  346. (tag_pattern2re_pattern(tag_pattern),
  347. ChunkString.IN_CHINK_PATTERN))
  348. RegexpChunkRule.__init__(self, regexp, '{\g<chunk>}', descr)
  349. def __repr__(self):
  350. """
  351. Return a string representation of this rule. It has the form::
  352. <ChunkRule: '<IN|VB.*>'>
  353. Note that this representation does not include the
  354. description string; that string can be accessed
  355. separately with the ``descr()`` method.
  356. :rtype: str
  357. """
  358. return '<ChunkRule: '+unicode_repr(self._pattern)+'>'
  359. @python_2_unicode_compatible
  360. class ChinkRule(RegexpChunkRule):
  361. """
  362. A rule specifying how to remove chinks to a ``ChunkString``,
  363. using a matching tag pattern. When applied to a
  364. ``ChunkString``, it will find any substring that matches this
  365. tag pattern and that is contained in a chunk, and remove it
  366. from that chunk, thus creating two new chunks.
  367. """
  368. def __init__(self, tag_pattern, descr):
  369. """
  370. Construct a new ``ChinkRule``.
  371. :type tag_pattern: str
  372. :param tag_pattern: This rule's tag pattern. When
  373. applied to a ``ChunkString``, this rule will
  374. find any substring that matches this tag pattern and that
  375. is contained in a chunk, and remove it from that chunk,
  376. thus creating two new chunks.
  377. :type descr: str
  378. :param descr: A short description of the purpose and/or effect
  379. of this rule.
  380. """
  381. self._pattern = tag_pattern
  382. regexp = re.compile('(?P<chink>%s)%s' %
  383. (tag_pattern2re_pattern(tag_pattern),
  384. ChunkString.IN_CHUNK_PATTERN))
  385. RegexpChunkRule.__init__(self, regexp, '}\g<chink>{', descr)
  386. def __repr__(self):
  387. """
  388. Return a string representation of this rule. It has the form::
  389. <ChinkRule: '<IN|VB.*>'>
  390. Note that this representation does not include the
  391. description string; that string can be accessed
  392. separately with the ``descr()`` method.
  393. :rtype: str
  394. """
  395. return '<ChinkRule: '+unicode_repr(self._pattern)+'>'
  396. @python_2_unicode_compatible
  397. class UnChunkRule(RegexpChunkRule):
  398. """
  399. A rule specifying how to remove chunks to a ``ChunkString``,
  400. using a matching tag pattern. When applied to a
  401. ``ChunkString``, it will find any complete chunk that matches this
  402. tag pattern, and un-chunk it.
  403. """
  404. def __init__(self, tag_pattern, descr):
  405. """
  406. Construct a new ``UnChunkRule``.
  407. :type tag_pattern: str
  408. :param tag_pattern: This rule's tag pattern. When
  409. applied to a ``ChunkString``, this rule will
  410. find any complete chunk that matches this tag pattern,
  411. and un-chunk it.
  412. :type descr: str
  413. :param descr: A short description of the purpose and/or effect
  414. of this rule.
  415. """
  416. self._pattern = tag_pattern
  417. regexp = re.compile('\{(?P<chunk>%s)\}' %
  418. tag_pattern2re_pattern(tag_pattern))
  419. RegexpChunkRule.__init__(self, regexp, '\g<chunk>', descr)
  420. def __repr__(self):
  421. """
  422. Return a string representation of this rule. It has the form::
  423. <UnChunkRule: '<IN|VB.*>'>
  424. Note that this representation does not include the
  425. description string; that string can be accessed
  426. separately with the ``descr()`` method.
  427. :rtype: str
  428. """
  429. return '<UnChunkRule: '+unicode_repr(self._pattern)+'>'
  430. @python_2_unicode_compatible
  431. class MergeRule(RegexpChunkRule):
  432. """
  433. A rule specifying how to merge chunks in a ``ChunkString``, using
  434. two matching tag patterns: a left pattern, and a right pattern.
  435. When applied to a ``ChunkString``, it will find any chunk whose end
  436. matches left pattern, and immediately followed by a chunk whose
  437. beginning matches right pattern. It will then merge those two
  438. chunks into a single chunk.
  439. """
  440. def __init__(self, left_tag_pattern, right_tag_pattern, descr):
  441. """
  442. Construct a new ``MergeRule``.
  443. :type right_tag_pattern: str
  444. :param right_tag_pattern: This rule's right tag
  445. pattern. When applied to a ``ChunkString``, this
  446. rule will find any chunk whose end matches
  447. ``left_tag_pattern``, and immediately followed by a chunk
  448. whose beginning matches this pattern. It will
  449. then merge those two chunks into a single chunk.
  450. :type left_tag_pattern: str
  451. :param left_tag_pattern: This rule's left tag
  452. pattern. When applied to a ``ChunkString``, this
  453. rule will find any chunk whose end matches
  454. this pattern, and immediately followed by a chunk
  455. whose beginning matches ``right_tag_pattern``. It will
  456. then merge those two chunks into a single chunk.
  457. :type descr: str
  458. :param descr: A short description of the purpose and/or effect
  459. of this rule.
  460. """
  461. # Ensure that the individual patterns are coherent. E.g., if
  462. # left='(' and right=')', then this will raise an exception:
  463. re.compile(tag_pattern2re_pattern(left_tag_pattern))
  464. re.compile(tag_pattern2re_pattern(right_tag_pattern))
  465. self._left_tag_pattern = left_tag_pattern
  466. self._right_tag_pattern = right_tag_pattern
  467. regexp = re.compile('(?P<left>%s)}{(?=%s)' %
  468. (tag_pattern2re_pattern(left_tag_pattern),
  469. tag_pattern2re_pattern(right_tag_pattern)))
  470. RegexpChunkRule.__init__(self, regexp, '\g<left>', descr)
  471. def __repr__(self):
  472. """
  473. Return a string representation of this rule. It has the form::
  474. <MergeRule: '<NN|DT|JJ>', '<NN|JJ>'>
  475. Note that this representation does not include the
  476. description string; that string can be accessed
  477. separately with the ``descr()`` method.
  478. :rtype: str
  479. """
  480. return ('<MergeRule: '+unicode_repr(self._left_tag_pattern)+', '+
  481. unicode_repr(self._right_tag_pattern)+'>')
  482. @python_2_unicode_compatible
  483. class SplitRule(RegexpChunkRule):
  484. """
  485. A rule specifying how to split chunks in a ``ChunkString``, using
  486. two matching tag patterns: a left pattern, and a right pattern.
  487. When applied to a ``ChunkString``, it will find any chunk that
  488. matches the left pattern followed by the right pattern. It will
  489. then split the chunk into two new chunks, at the point between the
  490. two pattern matches.
  491. """
  492. def __init__(self, left_tag_pattern, right_tag_pattern, descr):
  493. """
  494. Construct a new ``SplitRule``.
  495. :type right_tag_pattern: str
  496. :param right_tag_pattern: This rule's right tag
  497. pattern. When applied to a ``ChunkString``, this rule will
  498. find any chunk containing a substring that matches
  499. ``left_tag_pattern`` followed by this pattern. It will
  500. then split the chunk into two new chunks at the point
  501. between these two matching patterns.
  502. :type left_tag_pattern: str
  503. :param left_tag_pattern: This rule's left tag
  504. pattern. When applied to a ``ChunkString``, this rule will
  505. find any chunk containing a substring that matches this
  506. pattern followed by ``right_tag_pattern``. It will then
  507. split the chunk into two new chunks at the point between
  508. these two matching patterns.
  509. :type descr: str
  510. :param descr: A short description of the purpose and/or effect
  511. of this rule.
  512. """
  513. # Ensure that the individual patterns are coherent. E.g., if
  514. # left='(' and right=')', then this will raise an exception:
  515. re.compile(tag_pattern2re_pattern(left_tag_pattern))
  516. re.compile(tag_pattern2re_pattern(right_tag_pattern))
  517. self._left_tag_pattern = left_tag_pattern
  518. self._right_tag_pattern = right_tag_pattern
  519. regexp = re.compile('(?P<left>%s)(?=%s)' %
  520. (tag_pattern2re_pattern(left_tag_pattern),
  521. tag_pattern2re_pattern(right_tag_pattern)))
  522. RegexpChunkRule.__init__(self, regexp, r'\g<left>}{', descr)
  523. def __repr__(self):
  524. """
  525. Return a string representation of this rule. It has the form::
  526. <SplitRule: '<NN>', '<DT>'>
  527. Note that this representation does not include the
  528. description string; that string can be accessed
  529. separately with the ``descr()`` method.
  530. :rtype: str
  531. """
  532. return ('<SplitRule: '+unicode_repr(self._left_tag_pattern)+', '+
  533. unicode_repr(self._right_tag_pattern)+'>')
  534. @python_2_unicode_compatible
  535. class ExpandLeftRule(RegexpChunkRule):
  536. """
  537. A rule specifying how to expand chunks in a ``ChunkString`` to the left,
  538. using two matching tag patterns: a left pattern, and a right pattern.
  539. When applied to a ``ChunkString``, it will find any chunk whose beginning
  540. matches right pattern, and immediately preceded by a chink whose
  541. end matches left pattern. It will then expand the chunk to incorporate
  542. the new material on the left.
  543. """
  544. def __init__(self, left_tag_pattern, right_tag_pattern, descr):
  545. """
  546. Construct a new ``ExpandRightRule``.
  547. :type right_tag_pattern: str
  548. :param right_tag_pattern: This rule's right tag
  549. pattern. When applied to a ``ChunkString``, this
  550. rule will find any chunk whose beginning matches
  551. ``right_tag_pattern``, and immediately preceded by a chink
  552. whose end matches this pattern. It will
  553. then merge those two chunks into a single chunk.
  554. :type left_tag_pattern: str
  555. :param left_tag_pattern: This rule's left tag
  556. pattern. When applied to a ``ChunkString``, this
  557. rule will find any chunk whose beginning matches
  558. this pattern, and immediately preceded by a chink
  559. whose end matches ``left_tag_pattern``. It will
  560. then expand the chunk to incorporate the new material on the left.
  561. :type descr: str
  562. :param descr: A short description of the purpose and/or effect
  563. of this rule.
  564. """
  565. # Ensure that the individual patterns are coherent. E.g., if
  566. # left='(' and right=')', then this will raise an exception:
  567. re.compile(tag_pattern2re_pattern(left_tag_pattern))
  568. re.compile(tag_pattern2re_pattern(right_tag_pattern))
  569. self._left_tag_pattern = left_tag_pattern
  570. self._right_tag_pattern = right_tag_pattern
  571. regexp = re.compile('(?P<left>%s)\{(?P<right>%s)' %
  572. (tag_pattern2re_pattern(left_tag_pattern),
  573. tag_pattern2re_pattern(right_tag_pattern)))
  574. RegexpChunkRule.__init__(self, regexp, '{\g<left>\g<right>', descr)
  575. def __repr__(self):
  576. """
  577. Return a string representation of this rule. It has the form::
  578. <ExpandLeftRule: '<NN|DT|JJ>', '<NN|JJ>'>
  579. Note that this representation does not include the
  580. description string; that string can be accessed
  581. separately with the ``descr()`` method.
  582. :rtype: str
  583. """
  584. return ('<ExpandLeftRule: '+unicode_repr(self._left_tag_pattern)+', '+
  585. unicode_repr(self._right_tag_pattern)+'>')
  586. @python_2_unicode_compatible
  587. class ExpandRightRule(RegexpChunkRule):
  588. """
  589. A rule specifying how to expand chunks in a ``ChunkString`` to the
  590. right, using two matching tag patterns: a left pattern, and a
  591. right pattern. When applied to a ``ChunkString``, it will find any
  592. chunk whose end matches left pattern, and immediately followed by
  593. a chink whose beginning matches right pattern. It will then
  594. expand the chunk to incorporate the new material on the right.
  595. """
  596. def __init__(self, left_tag_pattern, right_tag_pattern, descr):
  597. """
  598. Construct a new ``ExpandRightRule``.
  599. :type right_tag_pattern: str
  600. :param right_tag_pattern: This rule's right tag
  601. pattern. When applied to a ``ChunkString``, this
  602. rule will find any chunk whose end matches
  603. ``left_tag_pattern``, and immediately followed by a chink
  604. whose beginning matches this pattern. It will
  605. then merge those two chunks into a single chunk.
  606. :type left_tag_pattern: str
  607. :param left_tag_pattern: This rule's left tag
  608. pattern. When applied to a ``ChunkString``, this
  609. rule will find any chunk whose end matches
  610. this pattern, and immediately followed by a chink
  611. whose beginning matches ``right_tag_pattern``. It will
  612. then expand the chunk to incorporate the new material on the right.
  613. :type descr: str
  614. :param descr: A short description of the purpose and/or effect
  615. of this rule.
  616. """
  617. # Ensure that the individual patterns are coherent. E.g., if
  618. # left='(' and right=')', then this will raise an exception:
  619. re.compile(tag_pattern2re_pattern(left_tag_pattern))
  620. re.compile(tag_pattern2re_pattern(right_tag_pattern))
  621. self._left_tag_pattern = left_tag_pattern
  622. self._right_tag_pattern = right_tag_pattern
  623. regexp = re.compile('(?P<left>%s)\}(?P<right>%s)' %
  624. (tag_pattern2re_pattern(left_tag_pattern),
  625. tag_pattern2re_pattern(right_tag_pattern)))
  626. RegexpChunkRule.__init__(self, regexp, '\g<left>\g<right>}', descr)
  627. def __repr__(self):
  628. """
  629. Return a string representation of this rule. It has the form::
  630. <ExpandRightRule: '<NN|DT|JJ>', '<NN|JJ>'>
  631. Note that this representation does not include the
  632. description string; that string can be accessed
  633. separately with the ``descr()`` method.
  634. :rtype: str
  635. """
  636. return ('<ExpandRightRule: '+unicode_repr(self._left_tag_pattern)+', '+
  637. unicode_repr(self._right_tag_pattern)+'>')
  638. @python_2_unicode_compatible
  639. class ChunkRuleWithContext(RegexpChunkRule):
  640. """
  641. A rule specifying how to add chunks to a ``ChunkString``, using
  642. three matching tag patterns: one for the left context, one for the
  643. chunk, and one for the right context. When applied to a
  644. ``ChunkString``, it will find any substring that matches the chunk
  645. tag pattern, is surrounded by substrings that match the two
  646. context patterns, and is not already part of a chunk; and create a
  647. new chunk containing the substring that matched the chunk tag
  648. pattern.
  649. Caveat: Both the left and right context are consumed when this
  650. rule matches; therefore, if you need to find overlapping matches,
  651. you will need to apply your rule more than once.
  652. """
  653. def __init__(self, left_context_tag_pattern, chunk_tag_pattern,
  654. right_context_tag_pattern, descr):
  655. """
  656. Construct a new ``ChunkRuleWithContext``.
  657. :type left_context_tag_pattern: str
  658. :param left_context_tag_pattern: A tag pattern that must match
  659. the left context of ``chunk_tag_pattern`` for this rule to
  660. apply.
  661. :type chunk_tag_pattern: str
  662. :param chunk_tag_pattern: A tag pattern that must match for this
  663. rule to apply. If the rule does apply, then this pattern
  664. also identifies the substring that will be made into a chunk.
  665. :type right_context_tag_pattern: str
  666. :param right_context_tag_pattern: A tag pattern that must match
  667. the right context of ``chunk_tag_pattern`` for this rule to
  668. apply.
  669. :type descr: str
  670. :param descr: A short description of the purpose and/or effect
  671. of this rule.
  672. """
  673. # Ensure that the individual patterns are coherent. E.g., if
  674. # left='(' and right=')', then this will raise an exception:
  675. re.compile(tag_pattern2re_pattern(left_context_tag_pattern))
  676. re.compile(tag_pattern2re_pattern(chunk_tag_pattern))
  677. re.compile(tag_pattern2re_pattern(right_context_tag_pattern))
  678. self._left_context_tag_pattern = left_context_tag_pattern
  679. self._chunk_tag_pattern = chunk_tag_pattern
  680. self._right_context_tag_pattern = right_context_tag_pattern
  681. regexp = re.compile('(?P<left>%s)(?P<chunk>%s)(?P<right>%s)%s' %
  682. (tag_pattern2re_pattern(left_context_tag_pattern),
  683. tag_pattern2re_pattern(chunk_tag_pattern),
  684. tag_pattern2re_pattern(right_context_tag_pattern),
  685. ChunkString.IN_CHINK_PATTERN))
  686. replacement = r'\g<left>{\g<chunk>}\g<right>'
  687. RegexpChunkRule.__init__(self, regexp, replacement, descr)
  688. def __repr__(self):
  689. """
  690. Return a string representation of this rule. It has the form::
  691. <ChunkRuleWithContext: '<IN>', '<NN>', '<DT>'>
  692. Note that this representation does not include the
  693. description string; that string can be accessed
  694. separately with the ``descr()`` method.
  695. :rtype: str
  696. """
  697. return '<ChunkRuleWithContext: %r, %r, %r>' % (
  698. self._left_context_tag_pattern, self._chunk_tag_pattern,
  699. self._right_context_tag_pattern)
  700. ##//////////////////////////////////////////////////////
  701. ## Tag Pattern Format Conversion
  702. ##//////////////////////////////////////////////////////
  703. # this should probably be made more strict than it is -- e.g., it
  704. # currently accepts 'foo'.
  705. CHUNK_TAG_PATTERN = re.compile(r'^((%s|<%s>)*)$' %
  706. ('[^\{\}<>]+',
  707. '[^\{\}<>]+'))
  708. def tag_pattern2re_pattern(tag_pattern):
  709. """
  710. Convert a tag pattern to a regular expression pattern. A "tag
  711. pattern" is a modified version of a regular expression, designed
  712. for matching sequences of tags. The differences between regular
  713. expression patterns and tag patterns are:
  714. - In tag patterns, ``'<'`` and ``'>'`` act as parentheses; so
  715. ``'<NN>+'`` matches one or more repetitions of ``'<NN>'``, not
  716. ``'<NN'`` followed by one or more repetitions of ``'>'``.
  717. - Whitespace in tag patterns is ignored. So
  718. ``'<DT> | <NN>'`` is equivalant to ``'<DT>|<NN>'``
  719. - In tag patterns, ``'.'`` is equivalant to ``'[^{}<>]'``; so
  720. ``'<NN.*>'`` matches any single tag starting with ``'NN'``.
  721. In particular, ``tag_pattern2re_pattern`` performs the following
  722. transformations on the given pattern:
  723. - Replace '.' with '[^<>{}]'
  724. - Remove any whitespace
  725. - Add extra parens around '<' and '>', to make '<' and '>' act
  726. like parentheses. E.g., so that in '<NN>+', the '+' has scope
  727. over the entire '<NN>'; and so that in '<NN|IN>', the '|' has
  728. scope over 'NN' and 'IN', but not '<' or '>'.
  729. - Check to make sure the resulting pattern is valid.
  730. :type tag_pattern: str
  731. :param tag_pattern: The tag pattern to convert to a regular
  732. expression pattern.
  733. :raise ValueError: If ``tag_pattern`` is not a valid tag pattern.
  734. In particular, ``tag_pattern`` should not include braces; and it
  735. should not contain nested or mismatched angle-brackets.
  736. :rtype: str
  737. :return: A regular expression pattern corresponding to
  738. ``tag_pattern``.
  739. """
  740. # Clean up the regular expression
  741. tag_pattern = re.sub(r'\s', '', tag_pattern)
  742. tag_pattern = re.sub(r'<', '(<(', tag_pattern)
  743. tag_pattern = re.sub(r'>', ')>)', tag_pattern)
  744. # Check the regular expression
  745. if not CHUNK_TAG_PATTERN.match(tag_pattern):
  746. raise ValueError('Bad tag pattern: %r' % tag_pattern)
  747. # Replace "." with CHUNK_TAG_CHAR.
  748. # We have to do this after, since it adds {}[]<>s, which would
  749. # confuse CHUNK_TAG_PATTERN.
  750. # PRE doesn't have lookback assertions, so reverse twice, and do
  751. # the pattern backwards (with lookahead assertions). This can be
  752. # made much cleaner once we can switch back to SRE.
  753. def reverse_str(str):
  754. lst = list(str)
  755. lst.reverse()
  756. return ''.join(lst)
  757. tc_rev = reverse_str(ChunkString.CHUNK_TAG_CHAR)
  758. reversed = reverse_str(tag_pattern)
  759. reversed = re.sub(r'\.(?!\\(\\\\)*($|[^\\]))', tc_rev, reversed)
  760. tag_pattern = reverse_str(reversed)
  761. return tag_pattern
  762. ##//////////////////////////////////////////////////////
  763. ## RegexpChunkParser
  764. ##//////////////////////////////////////////////////////
  765. @python_2_unicode_compatible
  766. class RegexpChunkParser(ChunkParserI):
  767. """
  768. A regular expression based chunk parser. ``RegexpChunkParser`` uses a
  769. sequence of "rules" to find chunks of a single type within a
  770. text. The chunking of the text is encoded using a ``ChunkString``,
  771. and each rule acts by modifying the chunking in the
  772. ``ChunkString``. The rules are all implemented using regular
  773. expression matching and substitution.
  774. The ``RegexpChunkRule`` class and its subclasses (``ChunkRule``,
  775. ``ChinkRule``, ``UnChunkRule``, ``MergeRule``, and ``SplitRule``)
  776. define the rules that are used by ``RegexpChunkParser``. Each rule
  777. defines an ``apply()`` method, which modifies the chunking encoded
  778. by a given ``ChunkString``.
  779. :type _rules: list(RegexpChunkRule)
  780. :ivar _rules: The list of rules that should be applied to a text.
  781. :type _trace: int
  782. :ivar _trace: The default level of tracing.
  783. """
  784. def __init__(self, rules, chunk_node='NP', top_node='S', trace=0):
  785. """
  786. Construct a new ``RegexpChunkParser``.
  787. :type rules: list(RegexpChunkRule)
  788. :param rules: The sequence of rules that should be used to
  789. generate the chunking for a tagged text.
  790. :type chunk_node: str
  791. :param chunk_node: The node value that should be used for
  792. chunk subtrees. This is typically a short string
  793. describing the type of information contained by the chunk,
  794. such as ``"NP"`` for base noun phrases.
  795. :type top_node: str
  796. :param top_node: The node value that should be used for the
  797. top node of the chunk structure.
  798. :type trace: int
  799. :param trace: The level of tracing that should be used when
  800. parsing a text. ``0`` will generate no tracing output;
  801. ``1`` will generate normal tracing output; and ``2`` or
  802. higher will generate verbose tracing output.
  803. """
  804. self._rules = rules
  805. self._trace = trace
  806. self._chunk_node = chunk_node
  807. self._top_node = top_node
  808. def _trace_apply(self, chunkstr, verbose):
  809. """
  810. Apply each rule of this ``RegexpChunkParser`` to ``chunkstr``, in
  811. turn. Generate trace output between each rule. If ``verbose``
  812. is true, then generate verbose output.
  813. :type chunkstr: ChunkString
  814. :param chunkstr: The chunk string to which each rule should be
  815. applied.
  816. :type verbose: bool
  817. :param verbose: Whether output should be verbose.
  818. :rtype: None
  819. """
  820. print('# Input:')
  821. print(chunkstr)
  822. for rule in self._rules:
  823. rule.apply(chunkstr)
  824. if verbose:
  825. print('#', rule.descr()+' ('+unicode_repr(rule)+'):')
  826. else:
  827. print('#', rule.descr()+':')
  828. print(chunkstr)
  829. def _notrace_apply(self, chunkstr):
  830. """
  831. Apply each rule of this ``RegexpChunkParser`` to ``chunkstr``, in
  832. turn.
  833. :param chunkstr: The chunk string to which each rule should be
  834. applied.
  835. :type chunkstr: ChunkString
  836. :rtype: None
  837. """
  838. for rule in self._rules:
  839. rule.apply(chunkstr)
  840. def parse(self, chunk_struct, trace=None):
  841. """
  842. :type chunk_struct: Tree
  843. :param chunk_struct: the chunk structure to be (further) chunked
  844. :type trace: int
  845. :param trace: The level of tracing that should be used when
  846. parsing a text. ``0`` will generate no tracing output;
  847. ``1`` will generate normal tracing output; and ``2`` or
  848. highter will generate verbose tracing output. This value
  849. overrides the trace level value that was given to the
  850. constructor.
  851. :rtype: Tree
  852. :return: a chunk structure that encodes the chunks in a given
  853. tagged sentence. A chunk is a non-overlapping linguistic
  854. group, such as a noun phrase. The set of chunks
  855. identified in the chunk structure depends on the rules
  856. used to define this ``RegexpChunkParser``.
  857. """
  858. if len(chunk_struct) == 0:
  859. print('Warning: parsing empty text')
  860. return Tree(self._top_node, [])
  861. try:
  862. chunk_struct.node
  863. except AttributeError:
  864. chunk_struct = Tree(self._top_node, chunk_struct)
  865. # Use the default trace value?
  866. if trace is None: trace = self._trace
  867. chunkstr = ChunkString(chunk_struct)
  868. # Apply the sequence of rules to the chunkstring.
  869. if trace:
  870. verbose = (trace>1)
  871. self._trace_apply(chunkstr, verbose)
  872. else:
  873. self._notrace_apply(chunkstr)
  874. # Use the chunkstring to create a chunk structure.
  875. return chunkstr.to_chunkstruct(self._chunk_node)
  876. def rules(self):
  877. """
  878. :return: the sequence of rules used by ``RegexpChunkParser``.
  879. :rtype: list(RegexpChunkRule)
  880. """
  881. return self._rules
  882. def __repr__(self):
  883. """
  884. :return: a concise string representation of this
  885. ``RegexpChunkParser``.
  886. :rtype: str
  887. """
  888. return "<RegexpChunkParser with %d rules>" % len(self._rules)
  889. def __str__(self):
  890. """
  891. :return: a verbose string representation of this ``RegexpChunkParser``.
  892. :rtype: str
  893. """
  894. s = "RegexpChunkParser with %d rules:\n" % len(self._rules)
  895. margin = 0
  896. for rule in self._rules:
  897. margin = max(margin, len(rule.descr()))
  898. if margin < 35:
  899. format = " %" + repr(-(margin+3)) + "s%s\n"
  900. else:
  901. format = " %s\n %s\n"
  902. for rule in self._rules:
  903. s += format % (rule.descr(), unicode_repr(rule))
  904. return s[:-1]
  905. ##//////////////////////////////////////////////////////
  906. ## Chunk Grammar
  907. ##//////////////////////////////////////////////////////
  908. @python_2_unicode_compatible
  909. class RegexpParser(ChunkParserI):
  910. """
  911. A grammar based chunk parser. ``chunk.RegexpParser`` uses a set of
  912. regular expression patterns to specify the behavior of the parser.
  913. The chunking of the text is encoded using a ``ChunkString``, and
  914. each rule acts by modifying the chunking in the ``ChunkString``.
  915. The rules are all implemented using regular expression matching
  916. and substitution.
  917. A grammar contains one or more clauses in the following form::
  918. NP:
  919. {<DT|JJ>} # chunk determiners and adjectives
  920. }<[\.VI].*>+{ # chink any tag beginning with V, I, or .
  921. <.*>}{<DT> # split a chunk at a determiner
  922. <DT|JJ>{}<NN.*> # merge chunk ending with det/adj
  923. # with one starting with a noun
  924. The patterns of a clause are executed in order. An earlier
  925. pattern may introduce a chunk boundary that prevents a later
  926. pattern from executing. Sometimes an individual pattern will
  927. match on multiple, overlapping extents of the input. As with
  928. regular expression substitution more generally, the chunker will
  929. identify the first match possible, then continue looking for matches
  930. after this one has ended.
  931. The clauses of a grammar are also executed in order. A cascaded
  932. chunk parser is one having more than one clause. The maximum depth
  933. of a parse tree created by this chunk parser is the same as the
  934. number of clauses in the grammar.
  935. When tracing is turned on, the comment portion of a line is displayed
  936. each time the corresponding pattern is applied.
  937. :type _start: str
  938. :ivar _start: The start symbol of the grammar (the root node of
  939. resulting trees)
  940. :type _stages: int
  941. :ivar _stages: The list of parsing stages corresponding to the grammar
  942. """
  943. def __init__(self, grammar, top_node='S', loop=1, trace=0):
  944. """
  945. Create a new chunk parser, from the given start state
  946. and set of chunk patterns.
  947. :param grammar: The grammar, or a list of RegexpChunkParser objects
  948. :type grammar: str or list(RegexpChunkParser)
  949. :param top_node: The top node of the tree being created
  950. :type top_node: str or Nonterminal
  951. :param loop: The number of times to run through the patterns
  952. :type loop: int
  953. :type trace: int
  954. :param trace: The level of tracing that should be used when
  955. parsing a text. ``0`` will generate no tracing output;
  956. ``1`` will generate normal tracing output; and ``2`` or
  957. higher will generate verbose tracing output.
  958. """
  959. self._trace = trace
  960. self._stages = []
  961. self._grammar = grammar
  962. self._loop = loop
  963. if isinstance(grammar, string_types):
  964. self._parse_grammar(grammar, top_node, trace)
  965. else:
  966. # Make sur the grammar looks like it has the right type:
  967. type_err = ('Expected string or list of RegexpChunkParsers '
  968. 'for the grammar.')
  969. try: grammar = list(grammar)
  970. except: raise TypeError(type_err)
  971. for elt in grammar:
  972. if not isinstance(elt, RegexpChunkParser):
  973. raise TypeError(type_err)
  974. self._stages = grammar
  975. def _parse_grammar(self, grammar, top_node, trace):
  976. """
  977. Helper function for __init__: parse the grammar if it is a
  978. string.
  979. """
  980. rules = []
  981. lhs = None
  982. for line in grammar.split('\n'):
  983. line = line.strip()
  984. # New stage begins if there's an unescaped ':'
  985. m = re.match('(?P<nonterminal>(\\.|[^:])*)(:(?P<rule>.*))', line)
  986. if m:
  987. # Record the stage that we just completed.
  988. self._add_stage(rules, lhs, top_node, trace)
  989. # Start a new stage.
  990. lhs = m.group('nonterminal').strip()
  991. rules = []
  992. line = m.group('rule').strip()
  993. # Skip blank & comment-only lines
  994. if line=='' or line.startswith('#'): continue
  995. # Add the rule
  996. rules.append(RegexpChunkRule.parse(line))
  997. # Record the final stage
  998. self._add_stage(rules, lhs, top_node, trace)
  999. def _add_stage(self, rules, lhs, top_node, trace):
  1000. """
  1001. Helper function for __init__: add a new stage to the parser.
  1002. """
  1003. if rules != []:
  1004. if not lhs:
  1005. raise ValueError('Expected stage marker (eg NP:)')
  1006. parser = RegexpChunkParser(rules, chunk_node=lhs,
  1007. top_node=top_node, trace=trace)
  1008. self._stages.append(parser)
  1009. def parse(self, chunk_struct, trace=None):
  1010. """
  1011. Apply the chunk parser to this input.
  1012. :type chunk_struct: Tree
  1013. :param chunk_struct: the chunk structure to be (further) chunked
  1014. (this tree is modified, and is also returned)
  1015. :type trace: int
  1016. :param trace: The level of tracing that should be used when
  1017. parsing a text. ``0`` will generate no tracing output;
  1018. ``1`` will generate normal tracing output; and ``2`` or
  1019. highter will generate verbose tracing output. This value
  1020. overrides the trace level value that was given to the
  1021. constructor.
  1022. :return: the chunked output.
  1023. :rtype: Tree
  1024. """
  1025. if trace is None: trace = self._trace
  1026. for i in range(self._loop):
  1027. for parser in self._stages:
  1028. chunk_struct = parser.parse(chunk_struct, trace=trace)
  1029. return chunk_struct
  1030. def __repr__(self):
  1031. """
  1032. :return: a concise string representation of this ``chunk.RegexpParser``.
  1033. :rtype: str
  1034. """
  1035. return "<chunk.RegexpParser with %d stages>" % len(self._stages)
  1036. def __str__(self):
  1037. """
  1038. :return: a verbose string representation of this
  1039. ``RegexpParser``.
  1040. :rtype: str
  1041. """
  1042. s = "chunk.RegexpParser with %d stages:\n" % len(self._stages)
  1043. margin = 0
  1044. for parser in self._stages:
  1045. s += "%s\n" % parser
  1046. return s[:-1]
  1047. ##//////////////////////////////////////////////////////
  1048. ## Demonstration code
  1049. ##//////////////////////////////////////////////////////
  1050. def demo_eval(chunkparser, text):
  1051. """
  1052. Demonstration code for evaluating a chunk parser, using a
  1053. ``ChunkScore``. This function assumes that ``text`` contains one
  1054. sentence per line, and that each sentence has the form expected by
  1055. ``tree.chunk``. It runs the given chunk parser on each sentence in
  1056. the text, and scores the result. It prints the final score
  1057. (precision, recall, and f-measure); and reports the set of chunks
  1058. that were missed and the set of chunks that were incorrect. (At
  1059. most 10 missing chunks and 10 incorrect chunks are reported).
  1060. :param chunkparser: The chunkparser to be tested
  1061. :type chunkparser: ChunkParserI
  1062. :param text: The chunked tagged text that should be used for
  1063. evaluation.
  1064. :type text: str
  1065. """

Large files files are truncated, but you can click here to view the full file