simple.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. # Natural Language Toolkit: Simple Tokenizers
  2. #
  3. # Copyright (C) 2001-2020 NLTK Project
  4. # Author: Edward Loper <edloper@gmail.com>
  5. # Steven Bird <stevenbird1@gmail.com>
  6. # URL: <http://nltk.sourceforge.net>
  7. # For license information, see LICENSE.TXT
  8. r"""
  9. Simple Tokenizers
  10. These tokenizers divide strings into substrings using the string
  11. ``split()`` method.
  12. When tokenizing using a particular delimiter string, use
  13. the string ``split()`` method directly, as this is more efficient.
  14. The simple tokenizers are *not* available as separate functions;
  15. instead, you should just use the string ``split()`` method directly:
  16. >>> s = "Good muffins cost $3.88\nin New York. Please buy me\ntwo of them.\n\nThanks."
  17. >>> s.split()
  18. ['Good', 'muffins', 'cost', '$3.88', 'in', 'New', 'York.',
  19. 'Please', 'buy', 'me', 'two', 'of', 'them.', 'Thanks.']
  20. >>> s.split(' ')
  21. ['Good', 'muffins', 'cost', '$3.88\nin', 'New', 'York.', '',
  22. 'Please', 'buy', 'me\ntwo', 'of', 'them.\n\nThanks.']
  23. >>> s.split('\n')
  24. ['Good muffins cost $3.88', 'in New York. Please buy me',
  25. 'two of them.', '', 'Thanks.']
  26. The simple tokenizers are mainly useful because they follow the
  27. standard ``TokenizerI`` interface, and so can be used with any code
  28. that expects a tokenizer. For example, these tokenizers can be used
  29. to specify the tokenization conventions when building a `CorpusReader`.
  30. """
  31. from nltk.tokenize.api import TokenizerI, StringTokenizer
  32. from nltk.tokenize.util import string_span_tokenize, regexp_span_tokenize
  33. class SpaceTokenizer(StringTokenizer):
  34. r"""Tokenize a string using the space character as a delimiter,
  35. which is the same as ``s.split(' ')``.
  36. >>> from nltk.tokenize import SpaceTokenizer
  37. >>> s = "Good muffins cost $3.88\nin New York. Please buy me\ntwo of them.\n\nThanks."
  38. >>> SpaceTokenizer().tokenize(s)
  39. ['Good', 'muffins', 'cost', '$3.88\nin', 'New', 'York.', '',
  40. 'Please', 'buy', 'me\ntwo', 'of', 'them.\n\nThanks.']
  41. """
  42. _string = " "
  43. class TabTokenizer(StringTokenizer):
  44. r"""Tokenize a string use the tab character as a delimiter,
  45. the same as ``s.split('\t')``.
  46. >>> from nltk.tokenize import TabTokenizer
  47. >>> TabTokenizer().tokenize('a\tb c\n\t d')
  48. ['a', 'b c\n', ' d']
  49. """
  50. _string = "\t"
  51. class CharTokenizer(StringTokenizer):
  52. """Tokenize a string into individual characters. If this functionality
  53. is ever required directly, use ``for char in string``.
  54. """
  55. def tokenize(self, s):
  56. return list(s)
  57. def span_tokenize(self, s):
  58. for i, j in enumerate(range(1, len(s) + 1)):
  59. yield i, j
  60. class LineTokenizer(TokenizerI):
  61. r"""Tokenize a string into its lines, optionally discarding blank lines.
  62. This is similar to ``s.split('\n')``.
  63. >>> from nltk.tokenize import LineTokenizer
  64. >>> s = "Good muffins cost $3.88\nin New York. Please buy me\ntwo of them.\n\nThanks."
  65. >>> LineTokenizer(blanklines='keep').tokenize(s)
  66. ['Good muffins cost $3.88', 'in New York. Please buy me',
  67. 'two of them.', '', 'Thanks.']
  68. >>> # same as [l for l in s.split('\n') if l.strip()]:
  69. >>> LineTokenizer(blanklines='discard').tokenize(s)
  70. ['Good muffins cost $3.88', 'in New York. Please buy me',
  71. 'two of them.', 'Thanks.']
  72. :param blanklines: Indicates how blank lines should be handled. Valid values are:
  73. - ``discard``: strip blank lines out of the token list before returning it.
  74. A line is considered blank if it contains only whitespace characters.
  75. - ``keep``: leave all blank lines in the token list.
  76. - ``discard-eof``: if the string ends with a newline, then do not generate
  77. a corresponding token ``''`` after that newline.
  78. """
  79. def __init__(self, blanklines="discard"):
  80. valid_blanklines = ("discard", "keep", "discard-eof")
  81. if blanklines not in valid_blanklines:
  82. raise ValueError(
  83. "Blank lines must be one of: %s" % " ".join(valid_blanklines)
  84. )
  85. self._blanklines = blanklines
  86. def tokenize(self, s):
  87. lines = s.splitlines()
  88. # If requested, strip off blank lines.
  89. if self._blanklines == "discard":
  90. lines = [l for l in lines if l.rstrip()]
  91. elif self._blanklines == "discard-eof":
  92. if lines and not lines[-1].strip():
  93. lines.pop()
  94. return lines
  95. # discard-eof not implemented
  96. def span_tokenize(self, s):
  97. if self._blanklines == "keep":
  98. for span in string_span_tokenize(s, r"\n"):
  99. yield span
  100. else:
  101. for span in regexp_span_tokenize(s, r"\n(\s+\n)*"):
  102. yield span
  103. ######################################################################
  104. # { Tokenization Functions
  105. ######################################################################
  106. # XXX: it is stated in module docs that there is no function versions
  107. def line_tokenize(text, blanklines="discard"):
  108. return LineTokenizer(blanklines).tokenize(text)