regexp.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # Natural Language Toolkit: Tokenizers
  2. #
  3. # Copyright (C) 2001-2020 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. import re
  56. from nltk.tokenize.api import TokenizerI
  57. from nltk.tokenize.util import regexp_span_tokenize
  58. class RegexpTokenizer(TokenizerI):
  59. """
  60. A tokenizer that splits a string using a regular expression, which
  61. matches either the tokens or the separators between tokens.
  62. >>> tokenizer = RegexpTokenizer('\w+|\$[\d\.]+|\S+')
  63. :type pattern: str
  64. :param pattern: The pattern used to build this tokenizer.
  65. (This pattern must not contain capturing parentheses;
  66. Use non-capturing parentheses, e.g. (?:...), instead)
  67. :type gaps: bool
  68. :param gaps: True if this tokenizer's pattern should be used
  69. to find separators between tokens; False if this
  70. tokenizer's pattern should be used to find the tokens
  71. themselves.
  72. :type discard_empty: bool
  73. :param discard_empty: True if any empty tokens `''`
  74. generated by the tokenizer should be discarded. Empty
  75. tokens can only be generated if `_gaps == True`.
  76. :type flags: int
  77. :param flags: The regexp flags used to compile this
  78. tokenizer's pattern. By default, the following flags are
  79. used: `re.UNICODE | re.MULTILINE | re.DOTALL`.
  80. """
  81. def __init__(
  82. self,
  83. pattern,
  84. gaps=False,
  85. discard_empty=True,
  86. flags=re.UNICODE | re.MULTILINE | re.DOTALL,
  87. ):
  88. # If they gave us a regexp object, extract the pattern.
  89. pattern = getattr(pattern, "pattern", pattern)
  90. self._pattern = pattern
  91. self._gaps = gaps
  92. self._discard_empty = discard_empty
  93. self._flags = flags
  94. self._regexp = None
  95. def _check_regexp(self):
  96. if self._regexp is None:
  97. self._regexp = re.compile(self._pattern, self._flags)
  98. def tokenize(self, text):
  99. self._check_regexp()
  100. # If our regexp matches gaps, use re.split:
  101. if self._gaps:
  102. if self._discard_empty:
  103. return [tok for tok in self._regexp.split(text) if tok]
  104. else:
  105. return self._regexp.split(text)
  106. # If our regexp matches tokens, use re.findall:
  107. else:
  108. return self._regexp.findall(text)
  109. def span_tokenize(self, text):
  110. self._check_regexp()
  111. if self._gaps:
  112. for left, right in regexp_span_tokenize(text, self._regexp):
  113. if not (self._discard_empty and left == right):
  114. yield left, right
  115. else:
  116. for m in re.finditer(self._regexp, text):
  117. yield m.span()
  118. def __repr__(self):
  119. return "%s(pattern=%r, gaps=%r, discard_empty=%r, flags=%r)" % (
  120. self.__class__.__name__,
  121. self._pattern,
  122. self._gaps,
  123. self._discard_empty,
  124. self._flags,
  125. )
  126. class WhitespaceTokenizer(RegexpTokenizer):
  127. r"""
  128. Tokenize a string on whitespace (space, tab, newline).
  129. In general, users should use the string ``split()`` method instead.
  130. >>> from nltk.tokenize import WhitespaceTokenizer
  131. >>> s = "Good muffins cost $3.88\nin New York. Please buy me\ntwo of them.\n\nThanks."
  132. >>> WhitespaceTokenizer().tokenize(s)
  133. ['Good', 'muffins', 'cost', '$3.88', 'in', 'New', 'York.',
  134. 'Please', 'buy', 'me', 'two', 'of', 'them.', 'Thanks.']
  135. """
  136. def __init__(self):
  137. RegexpTokenizer.__init__(self, r"\s+", gaps=True)
  138. class BlanklineTokenizer(RegexpTokenizer):
  139. """
  140. Tokenize a string, treating any sequence of blank lines as a delimiter.
  141. Blank lines are defined as lines containing no characters, except for
  142. space or tab characters.
  143. """
  144. def __init__(self):
  145. RegexpTokenizer.__init__(self, r"\s*\n\s*\n\s*", gaps=True)
  146. class WordPunctTokenizer(RegexpTokenizer):
  147. """
  148. Tokenize a text into a sequence of alphabetic and
  149. non-alphabetic characters, using the regexp ``\w+|[^\w\s]+``.
  150. >>> from nltk.tokenize import WordPunctTokenizer
  151. >>> s = "Good muffins cost $3.88\\nin New York. Please buy me\\ntwo of them.\\n\\nThanks."
  152. >>> WordPunctTokenizer().tokenize(s)
  153. ['Good', 'muffins', 'cost', '$', '3', '.', '88', 'in', 'New', 'York',
  154. '.', 'Please', 'buy', 'me', 'two', 'of', 'them', '.', 'Thanks', '.']
  155. """
  156. def __init__(self):
  157. RegexpTokenizer.__init__(self, r"\w+|[^\w\s]+")
  158. ######################################################################
  159. # { Tokenization Functions
  160. ######################################################################
  161. def regexp_tokenize(
  162. text,
  163. pattern,
  164. gaps=False,
  165. discard_empty=True,
  166. flags=re.UNICODE | re.MULTILINE | re.DOTALL,
  167. ):
  168. """
  169. Return a tokenized copy of *text*. See :class:`.RegexpTokenizer`
  170. for descriptions of the arguments.
  171. """
  172. tokenizer = RegexpTokenizer(pattern, gaps, discard_empty, flags)
  173. return tokenizer.tokenize(text)
  174. blankline_tokenize = BlanklineTokenizer().tokenize
  175. wordpunct_tokenize = WordPunctTokenizer().tokenize