nist.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. # -*- coding: utf-8 -*-
  2. # Natural Language Toolkit: Python port of the mteval-v14.pl tokenizer.
  3. #
  4. # Copyright (C) 2001-2015 NLTK Project
  5. # Author: Liling Tan (ported from ftp://jaguar.ncsl.nist.gov/mt/resources/mteval-v14.pl)
  6. # Contributors: Ozan Caglayan, Wiktor Stribizew
  7. #
  8. # URL: <http://nltk.sourceforge.net>
  9. # For license information, see LICENSE.TXT
  10. """
  11. This is a NLTK port of the tokenizer used in the NIST BLEU evaluation script,
  12. https://github.com/moses-smt/mosesdecoder/blob/master/scripts/generic/mteval-v14.pl#L926
  13. which was also ported into Python in
  14. https://github.com/lium-lst/nmtpy/blob/master/nmtpy/metrics/mtevalbleu.py#L162
  15. """
  16. from __future__ import unicode_literals
  17. import io
  18. import re
  19. from six import text_type
  20. from nltk.corpus import perluniprops
  21. from nltk.tokenize.api import TokenizerI
  22. from nltk.tokenize.util import xml_unescape
  23. class NISTTokenizer(TokenizerI):
  24. """
  25. This NIST tokenizer is sentence-based instead of the original
  26. paragraph-based tokenization from mteval-14.pl; The sentence-based
  27. tokenization is consistent with the other tokenizers available in NLTK.
  28. >>> from six import text_type
  29. >>> from nltk.tokenize.nist import NISTTokenizer
  30. >>> nist = NISTTokenizer()
  31. >>> s = "Good muffins cost $3.88 in New York."
  32. >>> expected_lower = [u'good', u'muffins', u'cost', u'$', u'3.88', u'in', u'new', u'york', u'.']
  33. >>> expected_cased = [u'Good', u'muffins', u'cost', u'$', u'3.88', u'in', u'New', u'York', u'.']
  34. >>> nist.tokenize(s, lowercase=False) == expected_cased
  35. True
  36. >>> nist.tokenize(s, lowercase=True) == expected_lower # Lowercased.
  37. True
  38. The international_tokenize() is the preferred function when tokenizing
  39. non-european text, e.g.
  40. >>> from nltk.tokenize.nist import NISTTokenizer
  41. >>> nist = NISTTokenizer()
  42. # Input strings.
  43. >>> albb = u'Alibaba Group Holding Limited (Chinese: 阿里巴巴集团控股 有限公司) us a Chinese e-commerce company...'
  44. >>> amz = u'Amazon.com, Inc. (/ˈæməzɒn/) is an American electronic commerce...'
  45. >>> rkt = u'Rakuten, Inc. (楽天株式会社 Rakuten Kabushiki-gaisha) is a Japanese electronic commerce and Internet company based in Tokyo.'
  46. # Expected tokens.
  47. >>> expected_albb = [u'Alibaba', u'Group', u'Holding', u'Limited', u'(', u'Chinese', u':', u'\u963f\u91cc\u5df4\u5df4\u96c6\u56e2\u63a7\u80a1', u'\u6709\u9650\u516c\u53f8', u')']
  48. >>> expected_amz = [u'Amazon', u'.', u'com', u',', u'Inc', u'.', u'(', u'/', u'\u02c8\xe6', u'm']
  49. >>> expected_rkt = [u'Rakuten', u',', u'Inc', u'.', u'(', u'\u697d\u5929\u682a\u5f0f\u4f1a\u793e', u'Rakuten', u'Kabushiki', u'-', u'gaisha']
  50. >>> nist.international_tokenize(albb)[:10] == expected_albb
  51. True
  52. >>> nist.international_tokenize(amz)[:10] == expected_amz
  53. True
  54. >>> nist.international_tokenize(rkt)[:10] == expected_rkt
  55. True
  56. # Doctest for patching issue #1926
  57. >>> sent = u'this is a foo\u2604sentence.'
  58. >>> expected_sent = [u'this', u'is', u'a', u'foo', u'\u2604', u'sentence', u'.']
  59. >>> nist.international_tokenize(sent) == expected_sent
  60. True
  61. """
  62. # Strip "skipped" tags
  63. STRIP_SKIP = re.compile('<skipped>'), ''
  64. # Strip end-of-line hyphenation and join lines
  65. STRIP_EOL_HYPHEN = re.compile(u'\u2028'), ' '
  66. # Tokenize punctuation.
  67. PUNCT = re.compile('([\{-\~\[-\` -\&\(-\+\:-\@\/])'), ' \\1 '
  68. # Tokenize period and comma unless preceded by a digit.
  69. PERIOD_COMMA_PRECEED = re.compile('([^0-9])([\.,])'), '\\1 \\2 '
  70. # Tokenize period and comma unless followed by a digit.
  71. PERIOD_COMMA_FOLLOW = re.compile('([\.,])([^0-9])'), ' \\1 \\2'
  72. # Tokenize dash when preceded by a digit
  73. DASH_PRECEED_DIGIT = re.compile('([0-9])(-)'), '\\1 \\2 '
  74. LANG_DEPENDENT_REGEXES = [
  75. PUNCT,
  76. PERIOD_COMMA_PRECEED,
  77. PERIOD_COMMA_FOLLOW,
  78. DASH_PRECEED_DIGIT,
  79. ]
  80. # Perluniprops characters used in NIST tokenizer.
  81. pup_number = text_type(''.join(set(perluniprops.chars('Number')))) # i.e. \p{N}
  82. pup_punct = text_type(''.join(set(perluniprops.chars('Punctuation')))) # i.e. \p{P}
  83. pup_symbol = text_type(''.join(set(perluniprops.chars('Symbol')))) # i.e. \p{S}
  84. # Python regexes needs to escape some special symbols, see
  85. # see https://stackoverflow.com/q/45670950/610569
  86. number_regex = re.sub(r'[]^\\-]', r'\\\g<0>', pup_number)
  87. punct_regex = re.sub(r'[]^\\-]', r'\\\g<0>', pup_punct)
  88. symbol_regex = re.sub(r'[]^\\-]', r'\\\g<0>', pup_symbol)
  89. # Note: In the original perl implementation, \p{Z} and \p{Zl} were used to
  90. # (i) strip trailing and heading spaces and
  91. # (ii) de-deuplicate spaces.
  92. # In Python, this would do: ' '.join(str.strip().split())
  93. # Thus, the next two lines were commented out.
  94. # Line_Separator = text_type(''.join(perluniprops.chars('Line_Separator'))) # i.e. \p{Zl}
  95. # Separator = text_type(''.join(perluniprops.chars('Separator'))) # i.e. \p{Z}
  96. # Pads non-ascii strings with space.
  97. NONASCII = re.compile('([\x00-\x7f]+)'), r' \1 '
  98. # Tokenize any punctuation unless followed AND preceded by a digit.
  99. PUNCT_1 = (
  100. re.compile(u"([{n}])([{p}])".format(n=number_regex, p=punct_regex)),
  101. '\\1 \\2 ',
  102. )
  103. PUNCT_2 = (
  104. re.compile(u"([{p}])([{n}])".format(n=number_regex, p=punct_regex)),
  105. ' \\1 \\2',
  106. )
  107. # Tokenize symbols
  108. SYMBOLS = re.compile(u"([{s}])".format(s=symbol_regex)), ' \\1 '
  109. INTERNATIONAL_REGEXES = [NONASCII, PUNCT_1, PUNCT_2, SYMBOLS]
  110. def lang_independent_sub(self, text):
  111. """Performs the language independent string substituitions. """
  112. # It's a strange order of regexes.
  113. # It'll be better to unescape after STRIP_EOL_HYPHEN
  114. # but let's keep it close to the original NIST implementation.
  115. regexp, substitution = self.STRIP_SKIP
  116. text = regexp.sub(substitution, text)
  117. text = xml_unescape(text)
  118. regexp, substitution = self.STRIP_EOL_HYPHEN
  119. text = regexp.sub(substitution, text)
  120. return text
  121. def tokenize(self, text, lowercase=False, western_lang=True, return_str=False):
  122. text = text_type(text)
  123. # Language independent regex.
  124. text = self.lang_independent_sub(text)
  125. # Language dependent regex.
  126. if western_lang:
  127. # Pad string with whitespace.
  128. text = ' ' + text + ' '
  129. if lowercase:
  130. text = text.lower()
  131. for regexp, substitution in self.LANG_DEPENDENT_REGEXES:
  132. text = regexp.sub(substitution, text)
  133. # Remove contiguous whitespaces.
  134. text = ' '.join(text.split())
  135. # Finally, strips heading and trailing spaces
  136. # and converts output string into unicode.
  137. text = text_type(text.strip())
  138. return text if return_str else text.split()
  139. def international_tokenize(
  140. self, text, lowercase=False, split_non_ascii=True, return_str=False
  141. ):
  142. text = text_type(text)
  143. # Different from the 'normal' tokenize(), STRIP_EOL_HYPHEN is applied
  144. # first before unescaping.
  145. regexp, substitution = self.STRIP_SKIP
  146. text = regexp.sub(substitution, text)
  147. regexp, substitution = self.STRIP_EOL_HYPHEN
  148. text = regexp.sub(substitution, text)
  149. text = xml_unescape(text)
  150. if lowercase:
  151. text = text.lower()
  152. for regexp, substitution in self.INTERNATIONAL_REGEXES:
  153. text = regexp.sub(substitution, text)
  154. # Make sure that there's only one space only between words.
  155. # Strip leading and trailing spaces.
  156. text = ' '.join(text.strip().split())
  157. return text if return_str else text.split()