regexp.py 53 KB

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