tokenize.doctest 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. .. Copyright (C) 2001-2019 NLTK Project
  2. .. For license information, see LICENSE.TXT
  3. >>> from __future__ import print_function
  4. >>> from nltk.tokenize import *
  5. Regression Tests: Treebank Tokenizer
  6. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  7. Some test strings.
  8. >>> s1 = "On a $50,000 mortgage of 30 years at 8 percent, the monthly payment would be $366.88."
  9. >>> word_tokenize(s1)
  10. ['On', 'a', '$', '50,000', 'mortgage', 'of', '30', 'years', 'at', '8', 'percent', ',', 'the', 'monthly', 'payment', 'would', 'be', '$', '366.88', '.']
  11. >>> s2 = "\"We beat some pretty good teams to get here,\" Slocum said."
  12. >>> word_tokenize(s2)
  13. ['``', 'We', 'beat', 'some', 'pretty', 'good', 'teams', 'to', 'get', 'here', ',', "''", 'Slocum', 'said', '.']
  14. >>> s3 = "Well, we couldn't have this predictable, cliche-ridden, \"Touched by an Angel\" (a show creator John Masius worked on) wanna-be if she didn't."
  15. >>> word_tokenize(s3)
  16. ['Well', ',', 'we', 'could', "n't", 'have', 'this', 'predictable', ',', 'cliche-ridden', ',', '``', 'Touched', 'by', 'an', 'Angel', "''", '(', 'a', 'show', 'creator', 'John', 'Masius', 'worked', 'on', ')', 'wanna-be', 'if', 'she', 'did', "n't", '.']
  17. >>> s4 = "I cannot cannot work under these conditions!"
  18. >>> word_tokenize(s4)
  19. ['I', 'can', 'not', 'can', 'not', 'work', 'under', 'these', 'conditions', '!']
  20. >>> s5 = "The company spent $30,000,000 last year."
  21. >>> word_tokenize(s5)
  22. ['The', 'company', 'spent', '$', '30,000,000', 'last', 'year', '.']
  23. >>> s6 = "The company spent 40.75% of its income last year."
  24. >>> word_tokenize(s6)
  25. ['The', 'company', 'spent', '40.75', '%', 'of', 'its', 'income', 'last', 'year', '.']
  26. >>> s7 = "He arrived at 3:00 pm."
  27. >>> word_tokenize(s7)
  28. ['He', 'arrived', 'at', '3:00', 'pm', '.']
  29. >>> s8 = "I bought these items: books, pencils, and pens."
  30. >>> word_tokenize(s8)
  31. ['I', 'bought', 'these', 'items', ':', 'books', ',', 'pencils', ',', 'and', 'pens', '.']
  32. >>> s9 = "Though there were 150, 100 of them were old."
  33. >>> word_tokenize(s9)
  34. ['Though', 'there', 'were', '150', ',', '100', 'of', 'them', 'were', 'old', '.']
  35. >>> s10 = "There were 300,000, but that wasn't enough."
  36. >>> word_tokenize(s10)
  37. ['There', 'were', '300,000', ',', 'but', 'that', 'was', "n't", 'enough', '.']
  38. Testing improvement made to the TreebankWordTokenizer
  39. >>> sx1 = u'\xabNow that I can do.\xbb'
  40. >>> expected = [u'\xab', u'Now', u'that', u'I', u'can', u'do', u'.', u'\xbb']
  41. >>> word_tokenize(sx1) == expected
  42. True
  43. >>> sx2 = u'The unicode 201C and 201D \u201cLEFT(RIGHT) DOUBLE QUOTATION MARK\u201d is also OPEN_PUNCT and CLOSE_PUNCT.'
  44. >>> expected = [u'The', u'unicode', u'201C', u'and', u'201D', u'\u201c', u'LEFT', u'(', u'RIGHT', u')', u'DOUBLE', u'QUOTATION', u'MARK', u'\u201d', u'is', u'also', u'OPEN_PUNCT', u'and', u'CLOSE_PUNCT', u'.']
  45. >>> word_tokenize(sx2) == expected
  46. True
  47. Sentence tokenization in word_tokenize:
  48. >>> s11 = "I called Dr. Jones. I called Dr. Jones."
  49. >>> word_tokenize(s11)
  50. ['I', 'called', 'Dr.', 'Jones', '.', 'I', 'called', 'Dr.', 'Jones', '.']
  51. >>> s12 = ("Ich muss unbedingt daran denken, Mehl, usw. fur einen "
  52. ... "Kuchen einzukaufen. Ich muss.")
  53. >>> word_tokenize(s12)
  54. ['Ich', 'muss', 'unbedingt', 'daran', 'denken', ',', 'Mehl', ',', 'usw',
  55. '.', 'fur', 'einen', 'Kuchen', 'einzukaufen', '.', 'Ich', 'muss', '.']
  56. >>> word_tokenize(s12, 'german')
  57. ['Ich', 'muss', 'unbedingt', 'daran', 'denken', ',', 'Mehl', ',', 'usw.',
  58. 'fur', 'einen', 'Kuchen', 'einzukaufen', '.', 'Ich', 'muss', '.']
  59. Regression Tests: Regexp Tokenizer
  60. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  61. Some additional test strings.
  62. >>> s = ("Good muffins cost $3.88\nin New York. Please buy me\n"
  63. ... "two of them.\n\nThanks.")
  64. >>> s2 = ("Alas, it has not rained today. When, do you think, "
  65. ... "will it rain again?")
  66. >>> s3 = ("<p>Although this is <b>not</b> the case here, we must "
  67. ... "not relax our vigilance!</p>")
  68. >>> regexp_tokenize(s2, r'[,\.\?!"]\s*', gaps=False)
  69. [', ', '. ', ', ', ', ', '?']
  70. >>> regexp_tokenize(s2, r'[,\.\?!"]\s*', gaps=True)
  71. ['Alas', 'it has not rained today', 'When', 'do you think',
  72. 'will it rain again']
  73. Take care to avoid using capturing groups:
  74. >>> regexp_tokenize(s3, r'</?[bp]>', gaps=False)
  75. ['<p>', '<b>', '</b>', '</p>']
  76. >>> regexp_tokenize(s3, r'</?(?:b|p)>', gaps=False)
  77. ['<p>', '<b>', '</b>', '</p>']
  78. >>> regexp_tokenize(s3, r'</?(?:b|p)>', gaps=True)
  79. ['Although this is ', 'not',
  80. ' the case here, we must not relax our vigilance!']
  81. Named groups are capturing groups, and confuse the tokenizer:
  82. >>> regexp_tokenize(s3, r'</?(?P<named>b|p)>', gaps=False)
  83. ['p', 'b', 'b', 'p']
  84. >>> regexp_tokenize(s3, r'</?(?P<named>b|p)>', gaps=True)
  85. ['p', 'Although this is ', 'b', 'not', 'b',
  86. ' the case here, we must not relax our vigilance!', 'p']
  87. Make sure that nested groups don't confuse the tokenizer:
  88. >>> regexp_tokenize(s2, r'(?:h|r|l)a(?:s|(?:i|n0))', gaps=False)
  89. ['las', 'has', 'rai', 'rai']
  90. >>> regexp_tokenize(s2, r'(?:h|r|l)a(?:s|(?:i|n0))', gaps=True)
  91. ['A', ', it ', ' not ', 'ned today. When, do you think, will it ',
  92. 'n again?']
  93. Back-references require capturing groups, and these are not supported:
  94. >>> regexp_tokenize("aabbbcccc", r'(.)\1')
  95. ['a', 'b', 'c', 'c']
  96. A simple sentence tokenizer '\.(\s+|$)'
  97. >>> regexp_tokenize(s, pattern=r'\.(?:\s+|$)', gaps=True)
  98. ['Good muffins cost $3.88\nin New York',
  99. 'Please buy me\ntwo of them', 'Thanks']
  100. Regression Tests: TweetTokenizer
  101. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  102. TweetTokenizer is a tokenizer specifically designed for micro-blogging tokenization tasks.
  103. >>> from nltk.tokenize import TweetTokenizer
  104. >>> tknzr = TweetTokenizer()
  105. >>> s0 = "This is a cooool #dummysmiley: :-) :-P <3 and some arrows < > -> <--"
  106. >>> tknzr.tokenize(s0)
  107. ['This', 'is', 'a', 'cooool', '#dummysmiley', ':', ':-)', ':-P', '<3', 'and', 'some', 'arrows', '<', '>', '->', '<--']
  108. >>> s1 = "@Joyster2012 @CathStaincliffe Good for you, girl!! Best wishes :-)"
  109. >>> tknzr.tokenize(s1)
  110. ['@Joyster2012', '@CathStaincliffe', 'Good', 'for', 'you', ',', 'girl', '!', '!', 'Best', 'wishes', ':-)']
  111. >>> s2 = "3Points for #DreamTeam Gooo BAILEY! :) #PBB737Gold @PBBabscbn"
  112. >>> tknzr.tokenize(s2)
  113. ['3Points', 'for', '#DreamTeam', 'Gooo', 'BAILEY', '!', ':)', '#PBB737Gold', '@PBBabscbn']
  114. >>> s3 = "@Insanomania They do... Their mentality doesn't :("
  115. >>> tknzr.tokenize(s3)
  116. ['@Insanomania', 'They', 'do', '...', 'Their', 'mentality', "doesn't", ':(']
  117. >>> s4 = "RT @facugambande: Ya por arrancar a grabar !!! #TirenTirenTiren vamoo !!"
  118. >>> tknzr.tokenize(s4)
  119. ['RT', '@facugambande', ':', 'Ya', 'por', 'arrancar', 'a', 'grabar', '!', '!', '!', '#TirenTirenTiren', 'vamoo', '!', '!']
  120. >>> tknzr = TweetTokenizer(reduce_len=True)
  121. >>> s5 = "@crushinghes the summer holidays are great but I'm so bored already :("
  122. >>> tknzr.tokenize(s5)
  123. ['@crushinghes', 'the', 'summer', 'holidays', 'are', 'great', 'but', "I'm", 'so', 'bored', 'already', ':(']
  124. It is possible to specify `strip_handles` and `reduce_len` parameters for a TweetTokenizer instance. Setting `strip_handles` to True, the tokenizer will remove Twitter handles (e.g. usernames). Setting `reduce_len` to True, repeated character sequences of length 3 or greater will be replaced with sequences of length 3.
  125. >>> tknzr = TweetTokenizer(strip_handles=True, reduce_len=True)
  126. >>> s6 = '@remy: This is waaaaayyyy too much for you!!!!!!'
  127. >>> tknzr.tokenize(s6)
  128. [':', 'This', 'is', 'waaayyy', 'too', 'much', 'for', 'you', '!', '!', '!']
  129. >>> s7 = '@_willy65: No place for @chuck tonight. Sorry.'
  130. >>> tknzr.tokenize(s7)
  131. [':', 'No', 'place', 'for', 'tonight', '.', 'Sorry', '.']
  132. >>> s8 = '@mar_tin is a great developer. Contact him at mar_tin@email.com.'
  133. >>> tknzr.tokenize(s8)
  134. ['is', 'a', 'great', 'developer', '.', 'Contact', 'him', 'at', 'mar_tin@email.com', '.']
  135. The `preserve_case` parameter (default: True) allows to convert uppercase tokens to lowercase tokens. Emoticons are not affected:
  136. >>> tknzr = TweetTokenizer(preserve_case=False)
  137. >>> s9 = "@jrmy: I'm REALLY HAPPYYY about that! NICEEEE :D :P"
  138. >>> tknzr.tokenize(s9)
  139. ['@jrmy', ':', "i'm", 'really', 'happyyy', 'about', 'that', '!', 'niceeee', ':D', ':P']
  140. It should not hang on long sequences of the same punctuation character.
  141. >>> tknzr = TweetTokenizer()
  142. >>> s10 = "Photo: Aujourd'hui sur http://t.co/0gebOFDUzn Projet... http://t.co/bKfIUbydz2.............................. http://fb.me/3b6uXpz0L"
  143. >>> tknzr.tokenize(s10)
  144. [u'Photo', u':', u"Aujourd'hui", u'sur', u'http://t.co/0gebOFDUzn', u'Projet', u'...', u'http://t.co/bKfIUbydz2', u'...', u'http://fb.me/3b6uXpz0L']
  145. Regression Tests: PunktSentenceTokenizer
  146. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  147. The sentence splitter should remove whitespace following the sentence boundary.
  148. >>> pst = PunktSentenceTokenizer()
  149. >>> pst.tokenize('See Section 3). Or Section 2). ')
  150. ['See Section 3).', 'Or Section 2).']
  151. >>> pst.tokenize('See Section 3.) Or Section 2.) ')
  152. ['See Section 3.)', 'Or Section 2.)']
  153. >>> pst.tokenize('See Section 3.) Or Section 2.) ', realign_boundaries=False)
  154. ['See Section 3.', ') Or Section 2.', ')']
  155. Two instances of PunktSentenceTokenizer should not share PunktParameters.
  156. >>> pst = PunktSentenceTokenizer()
  157. >>> pst2 = PunktSentenceTokenizer()
  158. >>> pst._params is pst2._params
  159. False
  160. Testing mutable default arguments for https://github.com/nltk/nltk/pull/2067
  161. >>> from nltk.tokenize.punkt import PunktBaseClass, PunktTrainer, PunktSentenceTokenizer
  162. >>> from nltk.tokenize.punkt import PunktLanguageVars, PunktParameters
  163. >>> pbc = PunktBaseClass(lang_vars=None, params=None)
  164. >>> type(pbc._params)
  165. <class 'nltk.tokenize.punkt.PunktParameters'>
  166. >>> type(pbc._lang_vars)
  167. <class 'nltk.tokenize.punkt.PunktLanguageVars'>
  168. >>> pt = PunktTrainer(lang_vars=None)
  169. >>> type(pt._lang_vars)
  170. <class 'nltk.tokenize.punkt.PunktLanguageVars'>
  171. >>> pst = PunktSentenceTokenizer(lang_vars=None)
  172. >>> type(pst._lang_vars)
  173. <class 'nltk.tokenize.punkt.PunktLanguageVars'>
  174. Regression Tests: align_tokens
  175. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  176. Post-hoc alignment of tokens with a source string
  177. >>> from nltk.tokenize.util import align_tokens
  178. >>> list(align_tokens([''], ""))
  179. [(0, 0)]
  180. >>> list(align_tokens([''], " "))
  181. [(0, 0)]
  182. >>> list(align_tokens([], ""))
  183. []
  184. >>> list(align_tokens([], " "))
  185. []
  186. >>> list(align_tokens(['a'], "a"))
  187. [(0, 1)]
  188. >>> list(align_tokens(['abc', 'def'], "abcdef"))
  189. [(0, 3), (3, 6)]
  190. >>> list(align_tokens(['abc', 'def'], "abc def"))
  191. [(0, 3), (4, 7)]
  192. >>> list(align_tokens(['ab', 'cd'], "ab cd ef"))
  193. [(0, 2), (3, 5)]
  194. >>> list(align_tokens(['ab', 'cd', 'ef'], "ab cd ef"))
  195. [(0, 2), (3, 5), (6, 8)]
  196. >>> list(align_tokens(['ab', 'cd', 'efg'], "ab cd ef"))
  197. Traceback (most recent call last):
  198. ....
  199. ValueError: substring "efg" not found in "ab cd ef"
  200. >>> list(align_tokens(['ab', 'cd', 'ef', 'gh'], "ab cd ef"))
  201. Traceback (most recent call last):
  202. ....
  203. ValueError: substring "gh" not found in "ab cd ef"
  204. >>> list(align_tokens(['The', 'plane', ',', 'bound', 'for', 'St', 'Petersburg', ',', 'crashed', 'in', 'Egypt', "'s", 'Sinai', 'desert', 'just', '23', 'minutes', 'after', 'take-off', 'from', 'Sharm', 'el-Sheikh', 'on', 'Saturday', '.'], "The plane, bound for St Petersburg, crashed in Egypt's Sinai desert just 23 minutes after take-off from Sharm el-Sheikh on Saturday."))
  205. [(0, 3), (4, 9), (9, 10), (11, 16), (17, 20), (21, 23), (24, 34), (34, 35), (36, 43), (44, 46), (47, 52), (52, 54), (55, 60), (61, 67), (68, 72), (73, 75), (76, 83), (84, 89), (90, 98), (99, 103), (104, 109), (110, 119), (120, 122), (123, 131), (131, 132)]
  206. Regression Tests: MWETokenizer
  207. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  208. Pickle an MWETokenizer
  209. >>> from nltk.tokenize import MWETokenizer
  210. >>> import pickle
  211. >>> tokenizer = MWETokenizer([('hors', "d'oeuvre")], separator='+')
  212. >>> p = pickle.dumps(tokenizer)
  213. >>> unpickeled = pickle.loads(p)
  214. >>> unpickeled.tokenize("An hors d'oeuvre tonight, sir?".split())
  215. ['An', "hors+d'oeuvre", 'tonight,', 'sir?']
  216. Regression Tests: TextTilingTokenizer
  217. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  218. TextTilingTokneizer tokenizes text into coherent subtopic chunks based upon Hearst's TextTiling algorithm.
  219. >>> from nltk.tokenize import TextTilingTokenizer
  220. >>> from nltk.corpus import brown
  221. >>> tt = TextTilingTokenizer()
  222. >>> tt.tokenize(brown.raw()[0:1000])
  223. ["\n\n\tThe/at Fulton/np-tl County/nn-tl Grand/jj-tl Jury/nn-tl said/vbd Friday/nr an/at investigation/nn of/in Atlanta's/np$ recent/jj primary/nn election/nn produced/vbd ``/`` no/at evidence/nn ''/'' that/cs any/dti irregularities/nns took/vbd place/nn ./.\n\n\n\tThe/at jury/nn further/rbr said/vbd in/in term-end/nn presentments/nns that/cs the/at City/nn-tl Executive/jj-tl Committee/nn-tl ,/, which/wdt had/hvd over-all/jj charge/nn of/in the/at election/nn ,/, ``/`` deserves/vbz the/at praise/nn and/cc thanks/nns of/in the/at City/nn-tl of/in-tl Atlanta/np-tl ''/'' for/in the/at manner/nn in/in which/wdt the/at election/nn was/bedz conducted/vbn ./.\n\n\n\tThe/at September-October/np term/nn jury/nn had/hvd been/ben charged/vbn by/in Fulton/np-tl Superior/jj-tl Court/nn-tl Judge/nn-tl Durwood/np Pye/np to/to investigate/vb reports/nns of/in possible/jj ``/`` irregularities/nns ''/'' in/in the/at hard-fought/jj primary/nn which/wdt was/bedz won/vbn by/in Mayor-nominate/nn-tl Ivan/np Allen/np Jr./"]
  224. Test that `ValueError` exceptions are raised when illegal arguments are used.
  225. >>> TextTilingTokenizer(similarity_method='foo').tokenize(brown.raw()[0:1000])
  226. Traceback (most recent call last):
  227. ...
  228. ValueError: Similarity method foo not recognized
  229. >>> TextTilingTokenizer(smoothing_method='bar').tokenize(brown.raw()[0:1000])
  230. Traceback (most recent call last):
  231. ...
  232. ValueError: Smoothing method bar not recognized