casual.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. # coding: utf-8
  2. #
  3. # Natural Language Toolkit: Twitter Tokenizer
  4. #
  5. # Copyright (C) 2001-2020 NLTK Project
  6. # Author: Christopher Potts <cgpotts@stanford.edu>
  7. # Ewan Klein <ewan@inf.ed.ac.uk> (modifications)
  8. # Pierpaolo Pantone <> (modifications)
  9. # URL: <http://nltk.org/>
  10. # For license information, see LICENSE.TXT
  11. #
  12. """
  13. Twitter-aware tokenizer, designed to be flexible and easy to adapt to new
  14. domains and tasks. The basic logic is this:
  15. 1. The tuple regex_strings defines a list of regular expression
  16. strings.
  17. 2. The regex_strings strings are put, in order, into a compiled
  18. regular expression object called word_re.
  19. 3. The tokenization is done by word_re.findall(s), where s is the
  20. user-supplied string, inside the tokenize() method of the class
  21. Tokenizer.
  22. 4. When instantiating Tokenizer objects, there is a single option:
  23. preserve_case. By default, it is set to True. If it is set to
  24. False, then the tokenizer will downcase everything except for
  25. emoticons.
  26. """
  27. ######################################################################
  28. import regex # https://github.com/nltk/nltk/issues/2409
  29. import html
  30. ######################################################################
  31. # The following strings are components in the regular expression
  32. # that is used for tokenizing. It's important that phone_number
  33. # appears first in the final regex (since it can contain whitespace).
  34. # It also could matter that tags comes after emoticons, due to the
  35. # possibility of having text like
  36. #
  37. # <:| and some text >:)
  38. #
  39. # Most importantly, the final element should always be last, since it
  40. # does a last ditch whitespace-based tokenization of whatever is left.
  41. # ToDo: Update with http://en.wikipedia.org/wiki/List_of_emoticons ?
  42. # This particular element is used in a couple ways, so we define it
  43. # with a name:
  44. EMOTICONS = r"""
  45. (?:
  46. [<>]?
  47. [:;=8] # eyes
  48. [\-o\*\']? # optional nose
  49. [\)\]\(\[dDpP/\:\}\{@\|\\] # mouth
  50. |
  51. [\)\]\(\[dDpP/\:\}\{@\|\\] # mouth
  52. [\-o\*\']? # optional nose
  53. [:;=8] # eyes
  54. [<>]?
  55. |
  56. <3 # heart
  57. )"""
  58. # URL pattern due to John Gruber, modified by Tom Winzig. See
  59. # https://gist.github.com/winzig/8894715
  60. URLS = r""" # Capture 1: entire matched URL
  61. (?:
  62. https?: # URL protocol and colon
  63. (?:
  64. /{1,3} # 1-3 slashes
  65. | # or
  66. [a-z0-9%] # Single letter or digit or '%'
  67. # (Trying not to match e.g. "URI::Escape")
  68. )
  69. | # or
  70. # looks like domain name followed by a slash:
  71. [a-z0-9.\-]+[.]
  72. (?:[a-z]{2,13})
  73. /
  74. )
  75. (?: # One or more:
  76. [^\s()<>{}\[\]]+ # Run of non-space, non-()<>{}[]
  77. | # or
  78. \([^\s()]*?\([^\s()]+\)[^\s()]*?\) # balanced parens, one level deep: (...(...)...)
  79. |
  80. \([^\s]+?\) # balanced parens, non-recursive: (...)
  81. )+
  82. (?: # End with:
  83. \([^\s()]*?\([^\s()]+\)[^\s()]*?\) # balanced parens, one level deep: (...(...)...)
  84. |
  85. \([^\s]+?\) # balanced parens, non-recursive: (...)
  86. | # or
  87. [^\s`!()\[\]{};:'".,<>?«»“”‘’] # not a space or one of these punct chars
  88. )
  89. | # OR, the following to match naked domains:
  90. (?:
  91. (?<!@) # not preceded by a @, avoid matching foo@_gmail.com_
  92. [a-z0-9]+
  93. (?:[.\-][a-z0-9]+)*
  94. [.]
  95. (?:[a-z]{2,13})
  96. \b
  97. /?
  98. (?!@) # not succeeded by a @,
  99. # avoid matching "foo.na" in "foo.na@example.com"
  100. )
  101. """
  102. # The components of the tokenizer:
  103. REGEXPS = (
  104. URLS,
  105. # Phone numbers:
  106. r"""
  107. (?:
  108. (?: # (international)
  109. \+?[01]
  110. [ *\-.\)]*
  111. )?
  112. (?: # (area code)
  113. [\(]?
  114. \d{3}
  115. [ *\-.\)]*
  116. )?
  117. \d{3} # exchange
  118. [ *\-.\)]*
  119. \d{4} # base
  120. )""",
  121. # ASCII Emoticons
  122. EMOTICONS,
  123. # HTML tags:
  124. r"""<[^>\s]+>""",
  125. # ASCII Arrows
  126. r"""[\-]+>|<[\-]+""",
  127. # Twitter username:
  128. r"""(?:@[\w_]+)""",
  129. # Twitter hashtags:
  130. r"""(?:\#+[\w_]+[\w\'_\-]*[\w_]+)""",
  131. # email addresses
  132. r"""[\w.+-]+@[\w-]+\.(?:[\w-]\.?)+[\w-]""",
  133. # Remaining word types:
  134. r"""
  135. (?:[^\W\d_](?:[^\W\d_]|['\-_])+[^\W\d_]) # Words with apostrophes or dashes.
  136. |
  137. (?:[+\-]?\d+[,/.:-]\d+[+\-]?) # Numbers, including fractions, decimals.
  138. |
  139. (?:[\w_]+) # Words without apostrophes or dashes.
  140. |
  141. (?:\.(?:\s*\.){1,}) # Ellipsis dots.
  142. |
  143. (?:\S) # Everything else that isn't whitespace.
  144. """,
  145. )
  146. ######################################################################
  147. # This is the core tokenizing regex:
  148. WORD_RE = regex.compile(r"""(%s)""" % "|".join(REGEXPS), regex.VERBOSE | regex.I | regex.UNICODE)
  149. # WORD_RE performs poorly on these patterns:
  150. HANG_RE = regex.compile(r"([^a-zA-Z0-9])\1{3,}")
  151. # The emoticon string gets its own regex so that we can preserve case for
  152. # them as needed:
  153. EMOTICON_RE = regex.compile(EMOTICONS, regex.VERBOSE | regex.I | regex.UNICODE)
  154. # These are for regularizing HTML entities to Unicode:
  155. ENT_RE = regex.compile(r"&(#?(x?))([^&;\s]+);")
  156. ######################################################################
  157. # Functions for converting html entities
  158. ######################################################################
  159. def _str_to_unicode(text, encoding=None, errors="strict"):
  160. if encoding is None:
  161. encoding = "utf-8"
  162. if isinstance(text, bytes):
  163. return text.decode(encoding, errors)
  164. return text
  165. def _replace_html_entities(text, keep=(), remove_illegal=True, encoding="utf-8"):
  166. """
  167. Remove entities from text by converting them to their
  168. corresponding unicode character.
  169. :param text: a unicode string or a byte string encoded in the given
  170. `encoding` (which defaults to 'utf-8').
  171. :param list keep: list of entity names which should not be replaced.\
  172. This supports both numeric entities (``&#nnnn;`` and ``&#hhhh;``)
  173. and named entities (such as ``&nbsp;`` or ``&gt;``).
  174. :param bool remove_illegal: If `True`, entities that can't be converted are\
  175. removed. Otherwise, entities that can't be converted are kept "as
  176. is".
  177. :returns: A unicode string with the entities removed.
  178. See https://github.com/scrapy/w3lib/blob/master/w3lib/html.py
  179. >>> from nltk.tokenize.casual import _replace_html_entities
  180. >>> _replace_html_entities(b'Price: &pound;100')
  181. 'Price: \\xa3100'
  182. >>> print(_replace_html_entities(b'Price: &pound;100'))
  183. Price: £100
  184. >>>
  185. """
  186. def _convert_entity(match):
  187. entity_body = match.group(3)
  188. if match.group(1):
  189. try:
  190. if match.group(2):
  191. number = int(entity_body, 16)
  192. else:
  193. number = int(entity_body, 10)
  194. # Numeric character references in the 80-9F range are typically
  195. # interpreted by browsers as representing the characters mapped
  196. # to bytes 80-9F in the Windows-1252 encoding. For more info
  197. # see: https://en.wikipedia.org/wiki/ISO/IEC_8859-1#Similar_character_sets
  198. if 0x80 <= number <= 0x9F:
  199. return bytes((number,)).decode("cp1252")
  200. except ValueError:
  201. number = None
  202. else:
  203. if entity_body in keep:
  204. return match.group(0)
  205. else:
  206. number = html.entities.name2codepoint.get(entity_body)
  207. if number is not None:
  208. try:
  209. return chr(number)
  210. except ValueError:
  211. pass
  212. return "" if remove_illegal else match.group(0)
  213. return ENT_RE.sub(_convert_entity, _str_to_unicode(text, encoding))
  214. ######################################################################
  215. class TweetTokenizer:
  216. r"""
  217. Tokenizer for tweets.
  218. >>> from nltk.tokenize import TweetTokenizer
  219. >>> tknzr = TweetTokenizer()
  220. >>> s0 = "This is a cooool #dummysmiley: :-) :-P <3 and some arrows < > -> <--"
  221. >>> tknzr.tokenize(s0)
  222. ['This', 'is', 'a', 'cooool', '#dummysmiley', ':', ':-)', ':-P', '<3', 'and', 'some', 'arrows', '<', '>', '->', '<--']
  223. Examples using `strip_handles` and `reduce_len parameters`:
  224. >>> tknzr = TweetTokenizer(strip_handles=True, reduce_len=True)
  225. >>> s1 = '@remy: This is waaaaayyyy too much for you!!!!!!'
  226. >>> tknzr.tokenize(s1)
  227. [':', 'This', 'is', 'waaayyy', 'too', 'much', 'for', 'you', '!', '!', '!']
  228. """
  229. def __init__(self, preserve_case=True, reduce_len=False, strip_handles=False):
  230. self.preserve_case = preserve_case
  231. self.reduce_len = reduce_len
  232. self.strip_handles = strip_handles
  233. def tokenize(self, text):
  234. """
  235. :param text: str
  236. :rtype: list(str)
  237. :return: a tokenized list of strings; concatenating this list returns\
  238. the original string if `preserve_case=False`
  239. """
  240. # Fix HTML character entities:
  241. text = _replace_html_entities(text)
  242. # Remove username handles
  243. if self.strip_handles:
  244. text = remove_handles(text)
  245. # Normalize word lengthening
  246. if self.reduce_len:
  247. text = reduce_lengthening(text)
  248. # Shorten problematic sequences of characters
  249. safe_text = HANG_RE.sub(r"\1\1\1", text)
  250. # Tokenize:
  251. words = WORD_RE.findall(safe_text)
  252. # Possibly alter the case, but avoid changing emoticons like :D into :d:
  253. if not self.preserve_case:
  254. words = list(
  255. map((lambda x: x if EMOTICON_RE.search(x) else x.lower()), words)
  256. )
  257. return words
  258. ######################################################################
  259. # Normalization Functions
  260. ######################################################################
  261. def reduce_lengthening(text):
  262. """
  263. Replace repeated character sequences of length 3 or greater with sequences
  264. of length 3.
  265. """
  266. pattern = regex.compile(r"(.)\1{2,}")
  267. return pattern.sub(r"\1\1\1", text)
  268. def remove_handles(text):
  269. """
  270. Remove Twitter username handles from text.
  271. """
  272. pattern = regex.compile(
  273. r"(?<![A-Za-z0-9_!@#\$%&*])@(([A-Za-z0-9_]){20}(?!@))|(?<![A-Za-z0-9_!@#\$%&*])@(([A-Za-z0-9_]){1,19})(?![A-Za-z0-9_]*@)"
  274. )
  275. # Substitute handles with ' ' to ensure that text on either side of removed handles are tokenized correctly
  276. return pattern.sub(" ", text)
  277. ######################################################################
  278. # Tokenization Function
  279. ######################################################################
  280. def casual_tokenize(text, preserve_case=True, reduce_len=False, strip_handles=False):
  281. """
  282. Convenience function for wrapping the tokenizer.
  283. """
  284. return TweetTokenizer(
  285. preserve_case=preserve_case, reduce_len=reduce_len, strip_handles=strip_handles
  286. ).tokenize(text)
  287. ###############################################################################