You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

665 lines
23 KiB

4 years ago
  1. # Natural Language Toolkit: Collections
  2. #
  3. # Copyright (C) 2001-2019 NLTK Project
  4. # Author: Steven Bird <stevenbird1@gmail.com>
  5. # URL: <http://nltk.org/>
  6. # For license information, see LICENSE.TXT
  7. from __future__ import print_function, absolute_import
  8. import bisect
  9. from itertools import islice, chain
  10. from functools import total_ordering
  11. # this unused import is for python 2.7
  12. from collections import defaultdict, deque, Counter
  13. from six import text_type
  14. from nltk.internals import slice_bounds, raise_unorderable_types
  15. from nltk.compat import python_2_unicode_compatible
  16. ##########################################################################
  17. # Ordered Dictionary
  18. ##########################################################################
  19. class OrderedDict(dict):
  20. def __init__(self, data=None, **kwargs):
  21. self._keys = self.keys(data, kwargs.get('keys'))
  22. self._default_factory = kwargs.get('default_factory')
  23. if data is None:
  24. dict.__init__(self)
  25. else:
  26. dict.__init__(self, data)
  27. def __delitem__(self, key):
  28. dict.__delitem__(self, key)
  29. self._keys.remove(key)
  30. def __getitem__(self, key):
  31. try:
  32. return dict.__getitem__(self, key)
  33. except KeyError:
  34. return self.__missing__(key)
  35. def __iter__(self):
  36. return (key for key in self.keys())
  37. def __missing__(self, key):
  38. if not self._default_factory and key not in self._keys:
  39. raise KeyError()
  40. return self._default_factory()
  41. def __setitem__(self, key, item):
  42. dict.__setitem__(self, key, item)
  43. if key not in self._keys:
  44. self._keys.append(key)
  45. def clear(self):
  46. dict.clear(self)
  47. self._keys.clear()
  48. def copy(self):
  49. d = dict.copy(self)
  50. d._keys = self._keys
  51. return d
  52. def items(self):
  53. # returns iterator under python 3 and list under python 2
  54. return zip(self.keys(), self.values())
  55. def keys(self, data=None, keys=None):
  56. if data:
  57. if keys:
  58. assert isinstance(keys, list)
  59. assert len(data) == len(keys)
  60. return keys
  61. else:
  62. assert (
  63. isinstance(data, dict)
  64. or isinstance(data, OrderedDict)
  65. or isinstance(data, list)
  66. )
  67. if isinstance(data, dict) or isinstance(data, OrderedDict):
  68. return data.keys()
  69. elif isinstance(data, list):
  70. return [key for (key, value) in data]
  71. elif '_keys' in self.__dict__:
  72. return self._keys
  73. else:
  74. return []
  75. def popitem(self):
  76. if not self._keys:
  77. raise KeyError()
  78. key = self._keys.pop()
  79. value = self[key]
  80. del self[key]
  81. return (key, value)
  82. def setdefault(self, key, failobj=None):
  83. dict.setdefault(self, key, failobj)
  84. if key not in self._keys:
  85. self._keys.append(key)
  86. def update(self, data):
  87. dict.update(self, data)
  88. for key in self.keys(data):
  89. if key not in self._keys:
  90. self._keys.append(key)
  91. def values(self):
  92. # returns iterator under python 3
  93. return map(self.get, self._keys)
  94. ######################################################################
  95. # Lazy Sequences
  96. ######################################################################
  97. @total_ordering
  98. @python_2_unicode_compatible
  99. class AbstractLazySequence(object):
  100. """
  101. An abstract base class for read-only sequences whose values are
  102. computed as needed. Lazy sequences act like tuples -- they can be
  103. indexed, sliced, and iterated over; but they may not be modified.
  104. The most common application of lazy sequences in NLTK is for
  105. corpus view objects, which provide access to the contents of a
  106. corpus without loading the entire corpus into memory, by loading
  107. pieces of the corpus from disk as needed.
  108. The result of modifying a mutable element of a lazy sequence is
  109. undefined. In particular, the modifications made to the element
  110. may or may not persist, depending on whether and when the lazy
  111. sequence caches that element's value or reconstructs it from
  112. scratch.
  113. Subclasses are required to define two methods: ``__len__()``
  114. and ``iterate_from()``.
  115. """
  116. def __len__(self):
  117. """
  118. Return the number of tokens in the corpus file underlying this
  119. corpus view.
  120. """
  121. raise NotImplementedError('should be implemented by subclass')
  122. def iterate_from(self, start):
  123. """
  124. Return an iterator that generates the tokens in the corpus
  125. file underlying this corpus view, starting at the token number
  126. ``start``. If ``start>=len(self)``, then this iterator will
  127. generate no tokens.
  128. """
  129. raise NotImplementedError('should be implemented by subclass')
  130. def __getitem__(self, i):
  131. """
  132. Return the *i* th token in the corpus file underlying this
  133. corpus view. Negative indices and spans are both supported.
  134. """
  135. if isinstance(i, slice):
  136. start, stop = slice_bounds(self, i)
  137. return LazySubsequence(self, start, stop)
  138. else:
  139. # Handle negative indices
  140. if i < 0:
  141. i += len(self)
  142. if i < 0:
  143. raise IndexError('index out of range')
  144. # Use iterate_from to extract it.
  145. try:
  146. return next(self.iterate_from(i))
  147. except StopIteration:
  148. raise IndexError('index out of range')
  149. def __iter__(self):
  150. """Return an iterator that generates the tokens in the corpus
  151. file underlying this corpus view."""
  152. return self.iterate_from(0)
  153. def count(self, value):
  154. """Return the number of times this list contains ``value``."""
  155. return sum(1 for elt in self if elt == value)
  156. def index(self, value, start=None, stop=None):
  157. """Return the index of the first occurrence of ``value`` in this
  158. list that is greater than or equal to ``start`` and less than
  159. ``stop``. Negative start and stop values are treated like negative
  160. slice bounds -- i.e., they count from the end of the list."""
  161. start, stop = slice_bounds(self, slice(start, stop))
  162. for i, elt in enumerate(islice(self, start, stop)):
  163. if elt == value:
  164. return i + start
  165. raise ValueError('index(x): x not in list')
  166. def __contains__(self, value):
  167. """Return true if this list contains ``value``."""
  168. return bool(self.count(value))
  169. def __add__(self, other):
  170. """Return a list concatenating self with other."""
  171. return LazyConcatenation([self, other])
  172. def __radd__(self, other):
  173. """Return a list concatenating other with self."""
  174. return LazyConcatenation([other, self])
  175. def __mul__(self, count):
  176. """Return a list concatenating self with itself ``count`` times."""
  177. return LazyConcatenation([self] * count)
  178. def __rmul__(self, count):
  179. """Return a list concatenating self with itself ``count`` times."""
  180. return LazyConcatenation([self] * count)
  181. _MAX_REPR_SIZE = 60
  182. def __repr__(self):
  183. """
  184. Return a string representation for this corpus view that is
  185. similar to a list's representation; but if it would be more
  186. than 60 characters long, it is truncated.
  187. """
  188. pieces = []
  189. length = 5
  190. for elt in self:
  191. pieces.append(repr(elt))
  192. length += len(pieces[-1]) + 2
  193. if length > self._MAX_REPR_SIZE and len(pieces) > 2:
  194. return '[%s, ...]' % text_type(', ').join(pieces[:-1])
  195. return '[%s]' % text_type(', ').join(pieces)
  196. def __eq__(self, other):
  197. return type(self) == type(other) and list(self) == list(other)
  198. def __ne__(self, other):
  199. return not self == other
  200. def __lt__(self, other):
  201. if type(other) != type(self):
  202. raise_unorderable_types("<", self, other)
  203. return list(self) < list(other)
  204. def __hash__(self):
  205. """
  206. :raise ValueError: Corpus view objects are unhashable.
  207. """
  208. raise ValueError('%s objects are unhashable' % self.__class__.__name__)
  209. class LazySubsequence(AbstractLazySequence):
  210. """
  211. A subsequence produced by slicing a lazy sequence. This slice
  212. keeps a reference to its source sequence, and generates its values
  213. by looking them up in the source sequence.
  214. """
  215. MIN_SIZE = 100
  216. """
  217. The minimum size for which lazy slices should be created. If
  218. ``LazySubsequence()`` is called with a subsequence that is
  219. shorter than ``MIN_SIZE``, then a tuple will be returned instead.
  220. """
  221. def __new__(cls, source, start, stop):
  222. """
  223. Construct a new slice from a given underlying sequence. The
  224. ``start`` and ``stop`` indices should be absolute indices --
  225. i.e., they should not be negative (for indexing from the back
  226. of a list) or greater than the length of ``source``.
  227. """
  228. # If the slice is small enough, just use a tuple.
  229. if stop - start < cls.MIN_SIZE:
  230. return list(islice(source.iterate_from(start), stop - start))
  231. else:
  232. return object.__new__(cls)
  233. def __init__(self, source, start, stop):
  234. self._source = source
  235. self._start = start
  236. self._stop = stop
  237. def __len__(self):
  238. return self._stop - self._start
  239. def iterate_from(self, start):
  240. return islice(
  241. self._source.iterate_from(start + self._start), max(0, len(self) - start)
  242. )
  243. class LazyConcatenation(AbstractLazySequence):
  244. """
  245. A lazy sequence formed by concatenating a list of lists. This
  246. underlying list of lists may itself be lazy. ``LazyConcatenation``
  247. maintains an index that it uses to keep track of the relationship
  248. between offsets in the concatenated lists and offsets in the
  249. sublists.
  250. """
  251. def __init__(self, list_of_lists):
  252. self._list = list_of_lists
  253. self._offsets = [0]
  254. def __len__(self):
  255. if len(self._offsets) <= len(self._list):
  256. for tok in self.iterate_from(self._offsets[-1]):
  257. pass
  258. return self._offsets[-1]
  259. def iterate_from(self, start_index):
  260. if start_index < self._offsets[-1]:
  261. sublist_index = bisect.bisect_right(self._offsets, start_index) - 1
  262. else:
  263. sublist_index = len(self._offsets) - 1
  264. index = self._offsets[sublist_index]
  265. # Construct an iterator over the sublists.
  266. if isinstance(self._list, AbstractLazySequence):
  267. sublist_iter = self._list.iterate_from(sublist_index)
  268. else:
  269. sublist_iter = islice(self._list, sublist_index, None)
  270. for sublist in sublist_iter:
  271. if sublist_index == (len(self._offsets) - 1):
  272. assert (
  273. index + len(sublist) >= self._offsets[-1]
  274. ), 'offests not monotonic increasing!'
  275. self._offsets.append(index + len(sublist))
  276. else:
  277. assert self._offsets[sublist_index + 1] == index + len(
  278. sublist
  279. ), 'inconsistent list value (num elts)'
  280. for value in sublist[max(0, start_index - index) :]:
  281. yield value
  282. index += len(sublist)
  283. sublist_index += 1
  284. class LazyMap(AbstractLazySequence):
  285. """
  286. A lazy sequence whose elements are formed by applying a given
  287. function to each element in one or more underlying lists. The
  288. function is applied lazily -- i.e., when you read a value from the
  289. list, ``LazyMap`` will calculate that value by applying its
  290. function to the underlying lists' value(s). ``LazyMap`` is
  291. essentially a lazy version of the Python primitive function
  292. ``map``. In particular, the following two expressions are
  293. equivalent:
  294. >>> from nltk.collections import LazyMap
  295. >>> function = str
  296. >>> sequence = [1,2,3]
  297. >>> map(function, sequence) # doctest: +SKIP
  298. ['1', '2', '3']
  299. >>> list(LazyMap(function, sequence))
  300. ['1', '2', '3']
  301. Like the Python ``map`` primitive, if the source lists do not have
  302. equal size, then the value None will be supplied for the
  303. 'missing' elements.
  304. Lazy maps can be useful for conserving memory, in cases where
  305. individual values take up a lot of space. This is especially true
  306. if the underlying list's values are constructed lazily, as is the
  307. case with many corpus readers.
  308. A typical example of a use case for this class is performing
  309. feature detection on the tokens in a corpus. Since featuresets
  310. are encoded as dictionaries, which can take up a lot of memory,
  311. using a ``LazyMap`` can significantly reduce memory usage when
  312. training and running classifiers.
  313. """
  314. def __init__(self, function, *lists, **config):
  315. """
  316. :param function: The function that should be applied to
  317. elements of ``lists``. It should take as many arguments
  318. as there are ``lists``.
  319. :param lists: The underlying lists.
  320. :param cache_size: Determines the size of the cache used
  321. by this lazy map. (default=5)
  322. """
  323. if not lists:
  324. raise TypeError('LazyMap requires at least two args')
  325. self._lists = lists
  326. self._func = function
  327. self._cache_size = config.get('cache_size', 5)
  328. self._cache = {} if self._cache_size > 0 else None
  329. # If you just take bool() of sum() here _all_lazy will be true just
  330. # in case n >= 1 list is an AbstractLazySequence. Presumably this
  331. # isn't what's intended.
  332. self._all_lazy = sum(
  333. isinstance(lst, AbstractLazySequence) for lst in lists
  334. ) == len(lists)
  335. def iterate_from(self, index):
  336. # Special case: one lazy sublist
  337. if len(self._lists) == 1 and self._all_lazy:
  338. for value in self._lists[0].iterate_from(index):
  339. yield self._func(value)
  340. return
  341. # Special case: one non-lazy sublist
  342. elif len(self._lists) == 1:
  343. while True:
  344. try:
  345. yield self._func(self._lists[0][index])
  346. except IndexError:
  347. return
  348. index += 1
  349. # Special case: n lazy sublists
  350. elif self._all_lazy:
  351. iterators = [lst.iterate_from(index) for lst in self._lists]
  352. while True:
  353. elements = []
  354. for iterator in iterators:
  355. try:
  356. elements.append(next(iterator))
  357. except: # FIXME: What is this except really catching? StopIteration?
  358. elements.append(None)
  359. if elements == [None] * len(self._lists):
  360. return
  361. yield self._func(*elements)
  362. index += 1
  363. # general case
  364. else:
  365. while True:
  366. try:
  367. elements = [lst[index] for lst in self._lists]
  368. except IndexError:
  369. elements = [None] * len(self._lists)
  370. for i, lst in enumerate(self._lists):
  371. try:
  372. elements[i] = lst[index]
  373. except IndexError:
  374. pass
  375. if elements == [None] * len(self._lists):
  376. return
  377. yield self._func(*elements)
  378. index += 1
  379. def __getitem__(self, index):
  380. if isinstance(index, slice):
  381. sliced_lists = [lst[index] for lst in self._lists]
  382. return LazyMap(self._func, *sliced_lists)
  383. else:
  384. # Handle negative indices
  385. if index < 0:
  386. index += len(self)
  387. if index < 0:
  388. raise IndexError('index out of range')
  389. # Check the cache
  390. if self._cache is not None and index in self._cache:
  391. return self._cache[index]
  392. # Calculate the value
  393. try:
  394. val = next(self.iterate_from(index))
  395. except StopIteration:
  396. raise IndexError('index out of range')
  397. # Update the cache
  398. if self._cache is not None:
  399. if len(self._cache) > self._cache_size:
  400. self._cache.popitem() # discard random entry
  401. self._cache[index] = val
  402. # Return the value
  403. return val
  404. def __len__(self):
  405. return max(len(lst) for lst in self._lists)
  406. class LazyZip(LazyMap):
  407. """
  408. A lazy sequence whose elements are tuples, each containing the i-th
  409. element from each of the argument sequences. The returned list is
  410. truncated in length to the length of the shortest argument sequence. The
  411. tuples are constructed lazily -- i.e., when you read a value from the
  412. list, ``LazyZip`` will calculate that value by forming a tuple from
  413. the i-th element of each of the argument sequences.
  414. ``LazyZip`` is essentially a lazy version of the Python primitive function
  415. ``zip``. In particular, an evaluated LazyZip is equivalent to a zip:
  416. >>> from nltk.collections import LazyZip
  417. >>> sequence1, sequence2 = [1, 2, 3], ['a', 'b', 'c']
  418. >>> zip(sequence1, sequence2) # doctest: +SKIP
  419. [(1, 'a'), (2, 'b'), (3, 'c')]
  420. >>> list(LazyZip(sequence1, sequence2))
  421. [(1, 'a'), (2, 'b'), (3, 'c')]
  422. >>> sequences = [sequence1, sequence2, [6,7,8,9]]
  423. >>> list(zip(*sequences)) == list(LazyZip(*sequences))
  424. True
  425. Lazy zips can be useful for conserving memory in cases where the argument
  426. sequences are particularly long.
  427. A typical example of a use case for this class is combining long sequences
  428. of gold standard and predicted values in a classification or tagging task
  429. in order to calculate accuracy. By constructing tuples lazily and
  430. avoiding the creation of an additional long sequence, memory usage can be
  431. significantly reduced.
  432. """
  433. def __init__(self, *lists):
  434. """
  435. :param lists: the underlying lists
  436. :type lists: list(list)
  437. """
  438. LazyMap.__init__(self, lambda *elts: elts, *lists)
  439. def iterate_from(self, index):
  440. iterator = LazyMap.iterate_from(self, index)
  441. while index < len(self):
  442. yield next(iterator)
  443. index += 1
  444. return
  445. def __len__(self):
  446. return min(len(lst) for lst in self._lists)
  447. class LazyEnumerate(LazyZip):
  448. """
  449. A lazy sequence whose elements are tuples, each ontaining a count (from
  450. zero) and a value yielded by underlying sequence. ``LazyEnumerate`` is
  451. useful for obtaining an indexed list. The tuples are constructed lazily
  452. -- i.e., when you read a value from the list, ``LazyEnumerate`` will
  453. calculate that value by forming a tuple from the count of the i-th
  454. element and the i-th element of the underlying sequence.
  455. ``LazyEnumerate`` is essentially a lazy version of the Python primitive
  456. function ``enumerate``. In particular, the following two expressions are
  457. equivalent:
  458. >>> from nltk.collections import LazyEnumerate
  459. >>> sequence = ['first', 'second', 'third']
  460. >>> list(enumerate(sequence))
  461. [(0, 'first'), (1, 'second'), (2, 'third')]
  462. >>> list(LazyEnumerate(sequence))
  463. [(0, 'first'), (1, 'second'), (2, 'third')]
  464. Lazy enumerations can be useful for conserving memory in cases where the
  465. argument sequences are particularly long.
  466. A typical example of a use case for this class is obtaining an indexed
  467. list for a long sequence of values. By constructing tuples lazily and
  468. avoiding the creation of an additional long sequence, memory usage can be
  469. significantly reduced.
  470. """
  471. def __init__(self, lst):
  472. """
  473. :param lst: the underlying list
  474. :type lst: list
  475. """
  476. LazyZip.__init__(self, range(len(lst)), lst)
  477. class LazyIteratorList(AbstractLazySequence):
  478. """
  479. Wraps an iterator, loading its elements on demand
  480. and making them subscriptable.
  481. __repr__ displays only the first few elements.
  482. """
  483. def __init__(self, it, known_len=None):
  484. self._it = it
  485. self._len = known_len
  486. self._cache = []
  487. def __len__(self):
  488. if self._len:
  489. return self._len
  490. for x in self.iterate_from(len(self._cache)):
  491. pass
  492. self._len = len(self._cache)
  493. return self._len
  494. def iterate_from(self, start):
  495. """Create a new iterator over this list starting at the given offset."""
  496. while len(self._cache) < start:
  497. v = next(self._it)
  498. self._cache.append(v)
  499. i = start
  500. while i < len(self._cache):
  501. yield self._cache[i]
  502. i += 1
  503. while True:
  504. v = next(self._it)
  505. self._cache.append(v)
  506. yield v
  507. i += 1
  508. def __add__(self, other):
  509. """Return a list concatenating self with other."""
  510. return type(self)(chain(self, other))
  511. def __radd__(self, other):
  512. """Return a list concatenating other with self."""
  513. return type(self)(chain(other, self))
  514. ######################################################################
  515. # Trie Implementation
  516. ######################################################################
  517. class Trie(dict):
  518. """A Trie implementation for strings"""
  519. LEAF = True
  520. def __init__(self, strings=None):
  521. """Builds a Trie object, which is built around a ``dict``
  522. If ``strings`` is provided, it will add the ``strings``, which
  523. consist of a ``list`` of ``strings``, to the Trie.
  524. Otherwise, it'll construct an empty Trie.
  525. :param strings: List of strings to insert into the trie
  526. (Default is ``None``)
  527. :type strings: list(str)
  528. """
  529. super(Trie, self).__init__()
  530. if strings:
  531. for string in strings:
  532. self.insert(string)
  533. def insert(self, string):
  534. """Inserts ``string`` into the Trie
  535. :param string: String to insert into the trie
  536. :type string: str
  537. :Example:
  538. >>> from nltk.collections import Trie
  539. >>> trie = Trie(["abc", "def"])
  540. >>> expected = {'a': {'b': {'c': {True: None}}}, \
  541. 'd': {'e': {'f': {True: None}}}}
  542. >>> trie == expected
  543. True
  544. """
  545. if len(string):
  546. self[string[0]].insert(string[1:])
  547. else:
  548. # mark the string is complete
  549. self[Trie.LEAF] = None
  550. def __missing__(self, key):
  551. self[key] = Trie()
  552. return self[key]