regexp.py 54 KB

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