regexp.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. # Natural Language Toolkit: Tokenizers
  2. #
  3. # Copyright (C) 2001-2019 NLTK Project
  4. # Author: Edward Loper <edloper@gmail.com>
  5. # Steven Bird <stevenbird1@gmail.com>
  6. # Trevor Cohn <tacohn@csse.unimelb.edu.au>
  7. # URL: <http://nltk.sourceforge.net>
  8. # For license information, see LICENSE.TXT
  9. r"""
  10. Regular-Expression Tokenizers
  11. A ``RegexpTokenizer`` splits a string into substrings using a regular expression.
  12. For example, the following tokenizer forms tokens out of alphabetic sequences,
  13. money expressions, and any other non-whitespace sequences:
  14. >>> from nltk.tokenize import RegexpTokenizer
  15. >>> s = "Good muffins cost $3.88\nin New York. Please buy me\ntwo of them.\n\nThanks."
  16. >>> tokenizer = RegexpTokenizer('\w+|\$[\d\.]+|\S+')
  17. >>> tokenizer.tokenize(s)
  18. ['Good', 'muffins', 'cost', '$3.88', 'in', 'New', 'York', '.',
  19. 'Please', 'buy', 'me', 'two', 'of', 'them', '.', 'Thanks', '.']
  20. A ``RegexpTokenizer`` can use its regexp to match delimiters instead:
  21. >>> tokenizer = RegexpTokenizer('\s+', gaps=True)
  22. >>> tokenizer.tokenize(s)
  23. ['Good', 'muffins', 'cost', '$3.88', 'in', 'New', 'York.',
  24. 'Please', 'buy', 'me', 'two', 'of', 'them.', 'Thanks.']
  25. Note that empty tokens are not returned when the delimiter appears at
  26. the start or end of the string.
  27. The material between the tokens is discarded. For example,
  28. the following tokenizer selects just the capitalized words:
  29. >>> capword_tokenizer = RegexpTokenizer('[A-Z]\w+')
  30. >>> capword_tokenizer.tokenize(s)
  31. ['Good', 'New', 'York', 'Please', 'Thanks']
  32. This module contains several subclasses of ``RegexpTokenizer``
  33. that use pre-defined regular expressions.
  34. >>> from nltk.tokenize import BlanklineTokenizer
  35. >>> # Uses '\s*\n\s*\n\s*':
  36. >>> BlanklineTokenizer().tokenize(s)
  37. ['Good muffins cost $3.88\nin New York. Please buy me\ntwo of them.',
  38. 'Thanks.']
  39. All of the regular expression tokenizers are also available as functions:
  40. >>> from nltk.tokenize import regexp_tokenize, wordpunct_tokenize, blankline_tokenize
  41. >>> regexp_tokenize(s, pattern='\w+|\$[\d\.]+|\S+')
  42. ['Good', 'muffins', 'cost', '$3.88', 'in', 'New', 'York', '.',
  43. 'Please', 'buy', 'me', 'two', 'of', 'them', '.', 'Thanks', '.']
  44. >>> wordpunct_tokenize(s)
  45. ['Good', 'muffins', 'cost', '$', '3', '.', '88', 'in', 'New', 'York',
  46. '.', 'Please', 'buy', 'me', 'two', 'of', 'them', '.', 'Thanks', '.']
  47. >>> blankline_tokenize(s)
  48. ['Good muffins cost $3.88\nin New York. Please buy me\ntwo of them.', 'Thanks.']
  49. Caution: The function ``regexp_tokenize()`` takes the text as its
  50. first argument, and the regular expression pattern as its second
  51. argument. This differs from the conventions used by Python's
  52. ``re`` functions, where the pattern is always the first argument.
  53. (This is for consistency with the other NLTK tokenizers.)
  54. """
  55. from __future__ import unicode_literals
  56. import re
  57. from nltk.tokenize.api import TokenizerI
  58. from nltk.tokenize.util import regexp_span_tokenize
  59. from nltk.compat import python_2_unicode_compatible
  60. @python_2_unicode_compatible
  61. class RegexpTokenizer(TokenizerI):
  62. """
  63. A tokenizer that splits a string using a regular expression, which
  64. matches either the tokens or the separators between tokens.
  65. >>> tokenizer = RegexpTokenizer('\w+|\$[\d\.]+|\S+')
  66. :type pattern: str
  67. :param pattern: The pattern used to build this tokenizer.
  68. (This pattern must not contain capturing parentheses;
  69. Use non-capturing parentheses, e.g. (?:...), instead)
  70. :type gaps: bool
  71. :param gaps: True if this tokenizer's pattern should be used
  72. to find separators between tokens; False if this
  73. tokenizer's pattern should be used to find the tokens
  74. themselves.
  75. :type discard_empty: bool
  76. :param discard_empty: True if any empty tokens `''`
  77. generated by the tokenizer should be discarded. Empty
  78. tokens can only be generated if `_gaps == True`.
  79. :type flags: int
  80. :param flags: The regexp flags used to compile this
  81. tokenizer's pattern. By default, the following flags are
  82. used: `re.UNICODE | re.MULTILINE | re.DOTALL`.
  83. """
  84. def __init__(
  85. self,
  86. pattern,
  87. gaps=False,
  88. discard_empty=True,
  89. flags=re.UNICODE | re.MULTILINE | re.DOTALL,
  90. ):
  91. # If they gave us a regexp object, extract the pattern.
  92. pattern = getattr(pattern, 'pattern', pattern)
  93. self._pattern = pattern
  94. self._gaps = gaps
  95. self._discard_empty = discard_empty
  96. self._flags = flags
  97. self._regexp = None
  98. def _check_regexp(self):
  99. if self._regexp is None:
  100. self._regexp = re.compile(self._pattern, self._flags)
  101. def tokenize(self, text):
  102. self._check_regexp()
  103. # If our regexp matches gaps, use re.split:
  104. if self._gaps:
  105. if self._discard_empty:
  106. return [tok for tok in self._regexp.split(text) if tok]
  107. else:
  108. return self._regexp.split(text)
  109. # If our regexp matches tokens, use re.findall:
  110. else:
  111. return self._regexp.findall(text)
  112. def span_tokenize(self, text):
  113. self._check_regexp()
  114. if self._gaps:
  115. for left, right in regexp_span_tokenize(text, self._regexp):
  116. if not (self._discard_empty and left == right):
  117. yield left, right
  118. else:
  119. for m in re.finditer(self._regexp, text):
  120. yield m.span()
  121. def __repr__(self):
  122. return '%s(pattern=%r, gaps=%r, discard_empty=%r, flags=%r)' % (
  123. self.__class__.__name__,
  124. self._pattern,
  125. self._gaps,
  126. self._discard_empty,
  127. self._flags,
  128. )
  129. class WhitespaceTokenizer(RegexpTokenizer):
  130. r"""
  131. Tokenize a string on whitespace (space, tab, newline).
  132. In general, users should use the string ``split()`` method instead.
  133. >>> from nltk.tokenize import WhitespaceTokenizer
  134. >>> s = "Good muffins cost $3.88\nin New York. Please buy me\ntwo of them.\n\nThanks."
  135. >>> WhitespaceTokenizer().tokenize(s)
  136. ['Good', 'muffins', 'cost', '$3.88', 'in', 'New', 'York.',
  137. 'Please', 'buy', 'me', 'two', 'of', 'them.', 'Thanks.']
  138. """
  139. def __init__(self):
  140. RegexpTokenizer.__init__(self, r'\s+', gaps=True)
  141. class BlanklineTokenizer(RegexpTokenizer):
  142. """
  143. Tokenize a string, treating any sequence of blank lines as a delimiter.
  144. Blank lines are defined as lines containing no characters, except for
  145. space or tab characters.
  146. """
  147. def __init__(self):
  148. RegexpTokenizer.__init__(self, r'\s*\n\s*\n\s*', gaps=True)
  149. class WordPunctTokenizer(RegexpTokenizer):
  150. """
  151. Tokenize a text into a sequence of alphabetic and
  152. non-alphabetic characters, using the regexp ``\w+|[^\w\s]+``.
  153. >>> from nltk.tokenize import WordPunctTokenizer
  154. >>> s = "Good muffins cost $3.88\\nin New York. Please buy me\\ntwo of them.\\n\\nThanks."
  155. >>> WordPunctTokenizer().tokenize(s)
  156. ['Good', 'muffins', 'cost', '$', '3', '.', '88', 'in', 'New', 'York',
  157. '.', 'Please', 'buy', 'me', 'two', 'of', 'them', '.', 'Thanks', '.']
  158. """
  159. def __init__(self):
  160. RegexpTokenizer.__init__(self, r'\w+|[^\w\s]+')
  161. ######################################################################
  162. # { Tokenization Functions
  163. ######################################################################
  164. def regexp_tokenize(
  165. text,
  166. pattern,
  167. gaps=False,
  168. discard_empty=True,
  169. flags=re.UNICODE | re.MULTILINE | re.DOTALL,
  170. ):
  171. """
  172. Return a tokenized copy of *text*. See :class:`.RegexpTokenizer`
  173. for descriptions of the arguments.
  174. """
  175. tokenizer = RegexpTokenizer(pattern, gaps, discard_empty, flags)
  176. return tokenizer.tokenize(text)
  177. blankline_tokenize = BlanklineTokenizer().tokenize
  178. wordpunct_tokenize = WordPunctTokenizer().tokenize