PageRenderTime 60ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/nltk/util.py

https://github.com/haewoon/nltk
Python | 1165 lines | 1008 code | 35 blank | 122 comment | 20 complexity | 772388e9a462b6e3e0ebf7f2556742c1 MD5 | raw file
Possible License(s): Apache-2.0
  1. # Natural Language Toolkit: Utility functions
  2. #
  3. # Copyright (C) 2001-2012 NLTK Project
  4. # Author: Steven Bird <sb@csse.unimelb.edu.au>
  5. # URL: <http://www.nltk.org/>
  6. # For license information, see LICENSE.TXT
  7. import locale
  8. import re
  9. import types
  10. import textwrap
  11. import pydoc
  12. import bisect
  13. import os
  14. from itertools import islice, chain
  15. from pprint import pprint
  16. from collections import defaultdict, deque
  17. from nltk.internals import slice_bounds
  18. ######################################################################
  19. # Short usage message
  20. ######################################################################
  21. def usage(obj, selfname='self'):
  22. import inspect
  23. str(obj) # In case it's lazy, this will load it.
  24. if not isinstance(obj, (types.TypeType, types.ClassType)):
  25. obj = obj.__class__
  26. print '%s supports the following operations:' % obj.__name__
  27. for (name, method) in sorted(pydoc.allmethods(obj).items()):
  28. if name.startswith('_'): continue
  29. if getattr(method, '__deprecated__', False): continue
  30. args, varargs, varkw, defaults = inspect.getargspec(method)
  31. if (args and args[0]=='self' and
  32. (defaults is None or len(args)>len(defaults))):
  33. args = args[1:]
  34. name = '%s.%s' % (selfname, name)
  35. argspec = inspect.formatargspec(
  36. args, varargs, varkw, defaults)
  37. print textwrap.fill('%s%s' % (name, argspec),
  38. initial_indent=' - ',
  39. subsequent_indent=' '*(len(name)+5))
  40. ##########################################################################
  41. # IDLE
  42. ##########################################################################
  43. def in_idle():
  44. """
  45. Return True if this function is run within idle. Tkinter
  46. programs that are run in idle should never call ``Tk.mainloop``; so
  47. this function should be used to gate all calls to ``Tk.mainloop``.
  48. :warning: This function works by checking ``sys.stdin``. If the
  49. user has modified ``sys.stdin``, then it may return incorrect
  50. results.
  51. :rtype: bool
  52. """
  53. import sys, types
  54. return (type(sys.stdin) == types.InstanceType and \
  55. sys.stdin.__class__.__name__ == 'PyShell')
  56. ##########################################################################
  57. # PRETTY PRINTING
  58. ##########################################################################
  59. def pr(data, start=0, end=None):
  60. """
  61. Pretty print a sequence of data items
  62. :param data: the data stream to print
  63. :type data: sequence or iter
  64. :param start: the start position
  65. :type start: int
  66. :param end: the end position
  67. :type end: int
  68. """
  69. pprint(list(islice(data, start, end)))
  70. def print_string(s, width=70):
  71. """
  72. Pretty print a string, breaking lines on whitespace
  73. :param s: the string to print, consisting of words and spaces
  74. :type s: str
  75. :param width: the display width
  76. :type width: int
  77. """
  78. print '\n'.join(textwrap.wrap(s, width=width))
  79. def tokenwrap(tokens, separator=" ", width=70):
  80. """
  81. Pretty print a list of text tokens, breaking lines on whitespace
  82. :param tokens: the tokens to print
  83. :type tokens: list
  84. :param separator: the string to use to separate tokens
  85. :type separator: str
  86. :param width: the display width (default=70)
  87. :type width: int
  88. """
  89. return '\n'.join(textwrap.wrap(separator.join(tokens), width=width))
  90. ##########################################################################
  91. # Indexing
  92. ##########################################################################
  93. class Index(defaultdict):
  94. def __init__(self, pairs):
  95. defaultdict.__init__(self, list)
  96. for key, value in pairs:
  97. self[key].append(value)
  98. ######################################################################
  99. ## Regexp display (thanks to David Mertz)
  100. ######################################################################
  101. def re_show(regexp, string, left="{", right="}"):
  102. """
  103. Return a string with markers surrounding the matched substrings.
  104. Search str for substrings matching ``regexp`` and wrap the matches
  105. with braces. This is convenient for learning about regular expressions.
  106. :param regexp: The regular expression.
  107. :type regexp: str
  108. :param string: The string being matched.
  109. :type string: str
  110. :param left: The left delimiter (printed before the matched substring)
  111. :type left: str
  112. :param right: The right delimiter (printed after the matched substring)
  113. :type right: str
  114. :rtype: str
  115. """
  116. print re.compile(regexp, re.M).sub(left + r"\g<0>" + right, string.rstrip())
  117. ##########################################################################
  118. # READ FROM FILE OR STRING
  119. ##########################################################################
  120. # recipe from David Mertz
  121. def filestring(f):
  122. if hasattr(f, 'read'):
  123. return f.read()
  124. elif isinstance(f, basestring):
  125. return open(f).read()
  126. else:
  127. raise ValueError, "Must be called with a filename or file-like object"
  128. ##########################################################################
  129. # Breadth-First Search
  130. ##########################################################################
  131. def breadth_first(tree, children=iter, maxdepth=-1):
  132. """Traverse the nodes of a tree in breadth-first order.
  133. (No need to check for cycles.)
  134. The first argument should be the tree root;
  135. children should be a function taking as argument a tree node
  136. and returning an iterator of the node's children.
  137. """
  138. queue = deque([(tree, 0)])
  139. while queue:
  140. node, depth = queue.popleft()
  141. yield node
  142. if depth != maxdepth:
  143. try:
  144. queue.extend((c, depth + 1) for c in children(node))
  145. except TypeError:
  146. pass
  147. ##########################################################################
  148. # Guess Character Encoding
  149. ##########################################################################
  150. # adapted from io.py in the docutils extension module (http://docutils.sourceforge.net)
  151. # http://www.pyzine.com/Issue008/Section_Articles/article_Encodings.html
  152. def guess_encoding(data):
  153. """
  154. Given a byte string, attempt to decode it.
  155. Tries the standard 'UTF8' and 'latin-1' encodings,
  156. Plus several gathered from locale information.
  157. The calling program *must* first call::
  158. locale.setlocale(locale.LC_ALL, '')
  159. If successful it returns ``(decoded_unicode, successful_encoding)``.
  160. If unsuccessful it raises a ``UnicodeError``.
  161. """
  162. successful_encoding = None
  163. # we make 'utf-8' the first encoding
  164. encodings = ['utf-8']
  165. #
  166. # next we add anything we can learn from the locale
  167. try:
  168. encodings.append(locale.nl_langinfo(locale.CODESET))
  169. except AttributeError:
  170. pass
  171. try:
  172. encodings.append(locale.getlocale()[1])
  173. except (AttributeError, IndexError):
  174. pass
  175. try:
  176. encodings.append(locale.getdefaultlocale()[1])
  177. except (AttributeError, IndexError):
  178. pass
  179. #
  180. # we try 'latin-1' last
  181. encodings.append('latin-1')
  182. for enc in encodings:
  183. # some of the locale calls
  184. # may have returned None
  185. if not enc:
  186. continue
  187. try:
  188. decoded = unicode(data, enc)
  189. successful_encoding = enc
  190. except (UnicodeError, LookupError):
  191. pass
  192. else:
  193. break
  194. if not successful_encoding:
  195. raise UnicodeError(
  196. 'Unable to decode input data. Tried the following encodings: %s.'
  197. % ', '.join([repr(enc) for enc in encodings if enc]))
  198. else:
  199. return (decoded, successful_encoding)
  200. ##########################################################################
  201. # Invert a dictionary
  202. ##########################################################################
  203. def invert_dict(d):
  204. inverted_dict = defaultdict(list)
  205. for key in d:
  206. if hasattr(d[key], '__iter__'):
  207. for term in d[key]:
  208. inverted_dict[term].append(key)
  209. else:
  210. inverted_dict[d[key]] = key
  211. return inverted_dict
  212. ##########################################################################
  213. # Utilities for directed graphs: transitive closure, and inversion
  214. # The graph is represented as a dictionary of sets
  215. ##########################################################################
  216. def transitive_closure(graph, reflexive=False):
  217. """
  218. Calculate the transitive closure of a directed graph,
  219. optionally the reflexive transitive closure.
  220. The algorithm is a slight modification of the "Marking Algorithm" of
  221. Ioannidis & Ramakrishnan (1998) "Efficient Transitive Closure Algorithms".
  222. :param graph: the initial graph, represented as a dictionary of sets
  223. :type graph: dict(set)
  224. :param reflexive: if set, also make the closure reflexive
  225. :type reflexive: bool
  226. :rtype: dict(set)
  227. """
  228. if reflexive:
  229. base_set = lambda k: set([k])
  230. else:
  231. base_set = lambda k: set()
  232. # The graph U_i in the article:
  233. agenda_graph = dict((k, v.copy()) for (k,v) in graph.iteritems())
  234. # The graph M_i in the article:
  235. closure_graph = dict((k, base_set(k)) for k in graph)
  236. for i in graph:
  237. agenda = agenda_graph[i]
  238. closure = closure_graph[i]
  239. while agenda:
  240. j = agenda.pop()
  241. closure.add(j)
  242. closure |= closure_graph.setdefault(j, base_set(j))
  243. agenda |= agenda_graph.get(j, base_set(j))
  244. agenda -= closure
  245. return closure_graph
  246. def invert_graph(graph):
  247. """
  248. Inverts a directed graph.
  249. :param graph: the graph, represented as a dictionary of sets
  250. :type graph: dict(set)
  251. :return: the inverted graph
  252. :rtype: dict(set)
  253. """
  254. inverted = {}
  255. for key, values in graph.iteritems():
  256. for value in values:
  257. inverted.setdefault(value, set()).add(key)
  258. return inverted
  259. ##########################################################################
  260. # HTML Cleaning
  261. ##########################################################################
  262. def clean_html(html):
  263. """
  264. Remove HTML markup from the given string.
  265. :param html: the HTML string to be cleaned
  266. :type html: str
  267. :rtype: str
  268. """
  269. # First we remove inline JavaScript/CSS:
  270. cleaned = re.sub(r"(?is)<(script|style).*?>.*?(</\1>)", "", html.strip())
  271. # Then we remove html comments. This has to be done before removing regular
  272. # tags since comments can contain '>' characters.
  273. cleaned = re.sub(r"(?s)<!--(.*?)-->[\n]?", "", cleaned)
  274. # Next we can remove the remaining tags:
  275. cleaned = re.sub(r"(?s)<.*?>", " ", cleaned)
  276. # Finally, we deal with whitespace
  277. cleaned = re.sub(r"&nbsp;", " ", cleaned)
  278. cleaned = re.sub(r" ", " ", cleaned)
  279. cleaned = re.sub(r" ", " ", cleaned)
  280. return cleaned.strip()
  281. def clean_url(url):
  282. from urllib import urlopen
  283. html = urlopen(url).read()
  284. return clean_html(html)
  285. ##########################################################################
  286. # FLATTEN LISTS
  287. ##########################################################################
  288. def flatten(*args):
  289. """
  290. Flatten a list.
  291. >>> from nltk.util import flatten
  292. >>> flatten(1, 2, ['b', 'a' , ['c', 'd']], 3)
  293. [1, 2, 'b', 'a', 'c', 'd', 3]
  294. :param args: items and lists to be combined into a single list
  295. :rtype: list
  296. """
  297. x = []
  298. for l in args:
  299. if not isinstance(l, (list, tuple)): l = [l]
  300. for item in l:
  301. if isinstance(item, (list, tuple)):
  302. x.extend(flatten(item))
  303. else:
  304. x.append(item)
  305. return x
  306. ##########################################################################
  307. # Ngram iteration
  308. ##########################################################################
  309. # add a flag to pad the sequence so we get peripheral ngrams?
  310. def ngrams(sequence, n, pad_left=False, pad_right=False, pad_symbol=None):
  311. """
  312. Return a sequence of ngrams from a sequence of items. For example:
  313. >>> from nltk.util import ngrams
  314. >>> ngrams([1,2,3,4,5], 3)
  315. [(1, 2, 3), (2, 3, 4), (3, 4, 5)]
  316. Use ingram for an iterator version of this function. Set pad_left
  317. or pad_right to true in order to get additional ngrams:
  318. >>> ngrams([1,2,3,4,5], 2, pad_right=True)
  319. [(1, 2), (2, 3), (3, 4), (4, 5), (5, None)]
  320. :param sequence: the source data to be converted into ngrams
  321. :type sequence: sequence or iter
  322. :param n: the degree of the ngrams
  323. :type n: int
  324. :param pad_left: whether the ngrams should be left-padded
  325. :type pad_left: bool
  326. :param pad_right: whether the ngrams should be right-padded
  327. :type pad_right: bool
  328. :param pad_symbol: the symbol to use for padding (default is None)
  329. :type pad_symbol: any
  330. :rtype: list(tuple)
  331. """
  332. if pad_left:
  333. sequence = chain((pad_symbol,) * (n-1), sequence)
  334. if pad_right:
  335. sequence = chain(sequence, (pad_symbol,) * (n-1))
  336. sequence = list(sequence)
  337. count = max(0, len(sequence) - n + 1)
  338. return [tuple(sequence[i:i+n]) for i in range(count)]
  339. def bigrams(sequence, **kwargs):
  340. """
  341. Return a sequence of bigrams from a sequence of items. For example:
  342. >>> from nltk.util import bigrams
  343. >>> bigrams([1,2,3,4,5])
  344. [(1, 2), (2, 3), (3, 4), (4, 5)]
  345. Use ibigrams for an iterator version of this function.
  346. :param sequence: the source data to be converted into bigrams
  347. :type sequence: sequence or iter
  348. :rtype: list(tuple)
  349. """
  350. return ngrams(sequence, 2, **kwargs)
  351. def trigrams(sequence, **kwargs):
  352. """
  353. Return a sequence of trigrams from a sequence of items. For example:
  354. >>> from nltk.util import trigrams
  355. >>> trigrams([1,2,3,4,5])
  356. [(1, 2, 3), (2, 3, 4), (3, 4, 5)]
  357. Use itrigrams for an iterator version of this function.
  358. :param sequence: the source data to be converted into trigrams
  359. :type sequence: sequence or iter
  360. :rtype: list(tuple)
  361. """
  362. return ngrams(sequence, 3, **kwargs)
  363. def ingrams(sequence, n, pad_left=False, pad_right=False, pad_symbol=None):
  364. """
  365. Return the ngrams generated from a sequence of items, as an iterator.
  366. For example:
  367. >>> from nltk.util import ingrams
  368. >>> list(ingrams([1,2,3,4,5], 3))
  369. [(1, 2, 3), (2, 3, 4), (3, 4, 5)]
  370. Use ngrams for a list version of this function. Set pad_left
  371. or pad_right to true in order to get additional ngrams:
  372. >>> list(ingrams([1,2,3,4,5], 2, pad_right=True))
  373. [(1, 2), (2, 3), (3, 4), (4, 5), (5, None)]
  374. :param sequence: the source data to be converted into ngrams
  375. :type sequence: sequence or iter
  376. :param n: the degree of the ngrams
  377. :type n: int
  378. :param pad_left: whether the ngrams should be left-padded
  379. :type pad_left: bool
  380. :param pad_right: whether the ngrams should be right-padded
  381. :type pad_right: bool
  382. :param pad_symbol: the symbol to use for padding (default is None)
  383. :type pad_symbol: any
  384. :rtype: iter(tuple)
  385. """
  386. sequence = iter(sequence)
  387. if pad_left:
  388. sequence = chain((pad_symbol,) * (n-1), sequence)
  389. if pad_right:
  390. sequence = chain(sequence, (pad_symbol,) * (n-1))
  391. history = []
  392. while n > 1:
  393. history.append(sequence.next())
  394. n -= 1
  395. for item in sequence:
  396. history.append(item)
  397. yield tuple(history)
  398. del history[0]
  399. def ibigrams(sequence, **kwargs):
  400. """
  401. Return the bigrams generated from a sequence of items, as an iterator.
  402. For example:
  403. >>> from nltk.util import ibigrams
  404. >>> list(ibigrams([1,2,3,4,5]))
  405. [(1, 2), (2, 3), (3, 4), (4, 5)]
  406. Use bigrams for a list version of this function.
  407. :param sequence: the source data to be converted into bigrams
  408. :type sequence: sequence or iter
  409. :rtype: iter(tuple)
  410. """
  411. for item in ingrams(sequence, 2, **kwargs):
  412. yield item
  413. def itrigrams(sequence, **kwargs):
  414. """
  415. Return the trigrams generated from a sequence of items, as an iterator.
  416. For example:
  417. >>> from nltk.util import itrigrams
  418. >>> list(itrigrams([1,2,3,4,5]))
  419. [(1, 2, 3), (2, 3, 4), (3, 4, 5)]
  420. Use trigrams for a list version of this function.
  421. :param sequence: the source data to be converted into trigrams
  422. :type sequence: sequence or iter
  423. :rtype: iter(tuple)
  424. """
  425. for item in ingrams(sequence, 3, **kwargs):
  426. yield item
  427. ##########################################################################
  428. # Ordered Dictionary
  429. ##########################################################################
  430. class OrderedDict(dict):
  431. def __init__(self, data=None, **kwargs):
  432. self._keys = self.keys(data, kwargs.get('keys'))
  433. self._default_factory = kwargs.get('default_factory')
  434. if data is None:
  435. dict.__init__(self)
  436. else:
  437. dict.__init__(self, data)
  438. def __delitem__(self, key):
  439. dict.__delitem__(self, key)
  440. self._keys.remove(key)
  441. def __getitem__(self, key):
  442. try:
  443. return dict.__getitem__(self, key)
  444. except KeyError:
  445. return self.__missing__(key)
  446. def __iter__(self):
  447. return (key for key in self.keys())
  448. def __missing__(self, key):
  449. if not self._default_factory and key not in self._keys:
  450. raise KeyError()
  451. else:
  452. return self._default_factory()
  453. def __setitem__(self, key, item):
  454. dict.__setitem__(self, key, item)
  455. if key not in self._keys:
  456. self._keys.append(key)
  457. def clear(self):
  458. dict.clear(self)
  459. self._keys.clear()
  460. def copy(self):
  461. d = dict.copy(self)
  462. d._keys = self._keys
  463. return d
  464. def items(self):
  465. return zip(self.keys(), self.values())
  466. def keys(self, data=None, keys=None):
  467. if data:
  468. if keys:
  469. assert isinstance(keys, list)
  470. assert len(data) == len(keys)
  471. return keys
  472. else:
  473. assert isinstance(data, dict) or \
  474. isinstance(data, OrderedDict) or \
  475. isinstance(data, list)
  476. if isinstance(data, dict) or isinstance(data, OrderedDict):
  477. return data.keys()
  478. elif isinstance(data, list):
  479. return [key for (key, value) in data]
  480. elif '_keys' in self.__dict__:
  481. return self._keys
  482. else:
  483. return []
  484. def popitem(self):
  485. if self._keys:
  486. key = self._keys.pop()
  487. value = self[key]
  488. del self[key]
  489. return (key, value)
  490. else:
  491. raise KeyError()
  492. def setdefault(self, key, failobj=None):
  493. dict.setdefault(self, key, failobj)
  494. if key not in self._keys:
  495. self._keys.append(key)
  496. def update(self, data):
  497. dict.update(self, data)
  498. for key in self.keys(data):
  499. if key not in self._keys:
  500. self._keys.append(key)
  501. def values(self):
  502. return map(self.get, self._keys)
  503. ######################################################################
  504. # Lazy Sequences
  505. ######################################################################
  506. class AbstractLazySequence(object):
  507. """
  508. An abstract base class for read-only sequences whose values are
  509. computed as needed. Lazy sequences act like tuples -- they can be
  510. indexed, sliced, and iterated over; but they may not be modified.
  511. The most common application of lazy sequences in NLTK is for
  512. corpus view objects, which provide access to the contents of a
  513. corpus without loading the entire corpus into memory, by loading
  514. pieces of the corpus from disk as needed.
  515. The result of modifying a mutable element of a lazy sequence is
  516. undefined. In particular, the modifications made to the element
  517. may or may not persist, depending on whether and when the lazy
  518. sequence caches that element's value or reconstructs it from
  519. scratch.
  520. Subclasses are required to define two methods: ``__len__()``
  521. and ``iterate_from()``.
  522. """
  523. def __len__(self):
  524. """
  525. Return the number of tokens in the corpus file underlying this
  526. corpus view.
  527. """
  528. raise NotImplementedError('should be implemented by subclass')
  529. def iterate_from(self, start):
  530. """
  531. Return an iterator that generates the tokens in the corpus
  532. file underlying this corpus view, starting at the token number
  533. ``start``. If ``start>=len(self)``, then this iterator will
  534. generate no tokens.
  535. """
  536. raise NotImplementedError('should be implemented by subclass')
  537. def __getitem__(self, i):
  538. """
  539. Return the *i* th token in the corpus file underlying this
  540. corpus view. Negative indices and spans are both supported.
  541. """
  542. if isinstance(i, slice):
  543. start, stop = slice_bounds(self, i)
  544. return LazySubsequence(self, start, stop)
  545. else:
  546. # Handle negative indices
  547. if i < 0: i += len(self)
  548. if i < 0: raise IndexError('index out of range')
  549. # Use iterate_from to extract it.
  550. try:
  551. return self.iterate_from(i).next()
  552. except StopIteration:
  553. raise IndexError('index out of range')
  554. def __iter__(self):
  555. """Return an iterator that generates the tokens in the corpus
  556. file underlying this corpus view."""
  557. return self.iterate_from(0)
  558. def count(self, value):
  559. """Return the number of times this list contains ``value``."""
  560. return sum(1 for elt in self if elt==value)
  561. def index(self, value, start=None, stop=None):
  562. """Return the index of the first occurrence of ``value`` in this
  563. list that is greater than or equal to ``start`` and less than
  564. ``stop``. Negative start and stop values are treated like negative
  565. slice bounds -- i.e., they count from the end of the list."""
  566. start, stop = slice_bounds(self, slice(start, stop))
  567. for i, elt in enumerate(islice(self, start, stop)):
  568. if elt == value: return i+start
  569. raise ValueError('index(x): x not in list')
  570. def __contains__(self, value):
  571. """Return true if this list contains ``value``."""
  572. return bool(self.count(value))
  573. def __add__(self, other):
  574. """Return a list concatenating self with other."""
  575. return LazyConcatenation([self, other])
  576. def __radd__(self, other):
  577. """Return a list concatenating other with self."""
  578. return LazyConcatenation([other, self])
  579. def __mul__(self, count):
  580. """Return a list concatenating self with itself ``count`` times."""
  581. return LazyConcatenation([self] * count)
  582. def __rmul__(self, count):
  583. """Return a list concatenating self with itself ``count`` times."""
  584. return LazyConcatenation([self] * count)
  585. _MAX_REPR_SIZE = 60
  586. def __repr__(self):
  587. """
  588. Return a string representation for this corpus view that is
  589. similar to a list's representation; but if it would be more
  590. than 60 characters long, it is truncated.
  591. """
  592. pieces = []
  593. length = 5
  594. for elt in self:
  595. pieces.append(repr(elt))
  596. length += len(pieces[-1]) + 2
  597. if length > self._MAX_REPR_SIZE and len(pieces) > 2:
  598. return '[%s, ...]' % ', '.join(pieces[:-1])
  599. else:
  600. return '[%s]' % ', '.join(pieces)
  601. def __cmp__(self, other):
  602. """
  603. Return a number indicating how ``self`` relates to other.
  604. - If ``other`` is not a corpus view or a list, return -1.
  605. - Otherwise, return ``cmp(list(self), list(other))``.
  606. Note: corpus views do not compare equal to tuples containing
  607. equal elements. Otherwise, transitivity would be violated,
  608. since tuples do not compare equal to lists.
  609. """
  610. if not isinstance(other, (AbstractLazySequence, list)): return -1
  611. return cmp(list(self), list(other))
  612. def __hash__(self):
  613. """
  614. :raise ValueError: Corpus view objects are unhashable.
  615. """
  616. raise ValueError('%s objects are unhashable' %
  617. self.__class__.__name__)
  618. class LazySubsequence(AbstractLazySequence):
  619. """
  620. A subsequence produced by slicing a lazy sequence. This slice
  621. keeps a reference to its source sequence, and generates its values
  622. by looking them up in the source sequence.
  623. """
  624. MIN_SIZE = 100
  625. """
  626. The minimum size for which lazy slices should be created. If
  627. ``LazySubsequence()`` is called with a subsequence that is
  628. shorter than ``MIN_SIZE``, then a tuple will be returned instead.
  629. """
  630. def __new__(cls, source, start, stop):
  631. """
  632. Construct a new slice from a given underlying sequence. The
  633. ``start`` and ``stop`` indices should be absolute indices --
  634. i.e., they should not be negative (for indexing from the back
  635. of a list) or greater than the length of ``source``.
  636. """
  637. # If the slice is small enough, just use a tuple.
  638. if stop-start < cls.MIN_SIZE:
  639. return list(islice(source.iterate_from(start), stop-start))
  640. else:
  641. return object.__new__(cls)
  642. def __init__(self, source, start, stop):
  643. self._source = source
  644. self._start = start
  645. self._stop = stop
  646. def __len__(self):
  647. return self._stop - self._start
  648. def iterate_from(self, start):
  649. return islice(self._source.iterate_from(start+self._start),
  650. max(0, len(self)-start))
  651. class LazyConcatenation(AbstractLazySequence):
  652. """
  653. A lazy sequence formed by concatenating a list of lists. This
  654. underlying list of lists may itself be lazy. ``LazyConcatenation``
  655. maintains an index that it uses to keep track of the relationship
  656. between offsets in the concatenated lists and offsets in the
  657. sublists.
  658. """
  659. def __init__(self, list_of_lists):
  660. self._list = list_of_lists
  661. self._offsets = [0]
  662. def __len__(self):
  663. if len(self._offsets) <= len(self._list):
  664. for tok in self.iterate_from(self._offsets[-1]): pass
  665. return self._offsets[-1]
  666. def iterate_from(self, start_index):
  667. if start_index < self._offsets[-1]:
  668. sublist_index = bisect.bisect_right(self._offsets, start_index)-1
  669. else:
  670. sublist_index = len(self._offsets)-1
  671. index = self._offsets[sublist_index]
  672. # Construct an iterator over the sublists.
  673. if isinstance(self._list, AbstractLazySequence):
  674. sublist_iter = self._list.iterate_from(sublist_index)
  675. else:
  676. sublist_iter = islice(self._list, sublist_index, None)
  677. for sublist in sublist_iter:
  678. if sublist_index == (len(self._offsets)-1):
  679. assert index+len(sublist) >= self._offsets[-1], (
  680. 'offests not monotonic increasing!')
  681. self._offsets.append(index+len(sublist))
  682. else:
  683. assert self._offsets[sublist_index+1] == index+len(sublist), (
  684. 'inconsistent list value (num elts)')
  685. for value in sublist[max(0, start_index-index):]:
  686. yield value
  687. index += len(sublist)
  688. sublist_index += 1
  689. class LazyMap(AbstractLazySequence):
  690. """
  691. A lazy sequence whose elements are formed by applying a given
  692. function to each element in one or more underlying lists. The
  693. function is applied lazily -- i.e., when you read a value from the
  694. list, ``LazyMap`` will calculate that value by applying its
  695. function to the underlying lists' value(s). ``LazyMap`` is
  696. essentially a lazy version of the Python primitive function
  697. ``map``. In particular, the following two expressions are
  698. equivalent:
  699. >>> from nltk.util import LazyMap
  700. >>> function = str
  701. >>> sequence = [1,2,3]
  702. >>> map(function, sequence)
  703. ['1', '2', '3']
  704. >>> list(LazyMap(function, sequence))
  705. ['1', '2', '3']
  706. Like the Python ``map`` primitive, if the source lists do not have
  707. equal size, then the value None will be supplied for the
  708. 'missing' elements.
  709. Lazy maps can be useful for conserving memory, in cases where
  710. individual values take up a lot of space. This is especially true
  711. if the underlying list's values are constructed lazily, as is the
  712. case with many corpus readers.
  713. A typical example of a use case for this class is performing
  714. feature detection on the tokens in a corpus. Since featuresets
  715. are encoded as dictionaries, which can take up a lot of memory,
  716. using a ``LazyMap`` can significantly reduce memory usage when
  717. training and running classifiers.
  718. """
  719. def __init__(self, function, *lists, **config):
  720. """
  721. :param function: The function that should be applied to
  722. elements of ``lists``. It should take as many arguments
  723. as there are ``lists``.
  724. :param lists: The underlying lists.
  725. :param cache_size: Determines the size of the cache used
  726. by this lazy map. (default=5)
  727. """
  728. if not lists:
  729. raise TypeError('LazyMap requires at least two args')
  730. self._lists = lists
  731. self._func = function
  732. self._cache_size = config.get('cache_size', 5)
  733. if self._cache_size > 0:
  734. self._cache = {}
  735. else:
  736. self._cache = None
  737. # If you just take bool() of sum() here _all_lazy will be true just
  738. # in case n >= 1 list is an AbstractLazySequence. Presumably this
  739. # isn't what's intended.
  740. self._all_lazy = sum(isinstance(lst, AbstractLazySequence)
  741. for lst in lists) == len(lists)
  742. def iterate_from(self, index):
  743. # Special case: one lazy sublist
  744. if len(self._lists) == 1 and self._all_lazy:
  745. for value in self._lists[0].iterate_from(index):
  746. yield self._func(value)
  747. return
  748. # Special case: one non-lazy sublist
  749. elif len(self._lists) == 1:
  750. while True:
  751. try: yield self._func(self._lists[0][index])
  752. except IndexError: return
  753. index += 1
  754. # Special case: n lazy sublists
  755. elif self._all_lazy:
  756. iterators = [lst.iterate_from(index) for lst in self._lists]
  757. while True:
  758. elements = []
  759. for iterator in iterators:
  760. try: elements.append(iterator.next())
  761. except: elements.append(None)
  762. if elements == [None] * len(self._lists):
  763. return
  764. yield self._func(*elements)
  765. index += 1
  766. # general case
  767. else:
  768. while True:
  769. try: elements = [lst[index] for lst in self._lists]
  770. except IndexError:
  771. elements = [None] * len(self._lists)
  772. for i, lst in enumerate(self._lists):
  773. try: elements[i] = lst[index]
  774. except IndexError: pass
  775. if elements == [None] * len(self._lists):
  776. return
  777. yield self._func(*elements)
  778. index += 1
  779. def __getitem__(self, index):
  780. if isinstance(index, slice):
  781. sliced_lists = [lst[index] for lst in self._lists]
  782. return LazyMap(self._func, *sliced_lists)
  783. else:
  784. # Handle negative indices
  785. if index < 0: index += len(self)
  786. if index < 0: raise IndexError('index out of range')
  787. # Check the cache
  788. if self._cache is not None and index in self._cache:
  789. return self._cache[index]
  790. # Calculate the value
  791. try: val = self.iterate_from(index).next()
  792. except StopIteration:
  793. raise IndexError('index out of range')
  794. # Update the cache
  795. if self._cache is not None:
  796. if len(self._cache) > self._cache_size:
  797. self._cache.popitem() # discard random entry
  798. self._cache[index] = val
  799. # Return the value
  800. return val
  801. def __len__(self):
  802. return max(len(lst) for lst in self._lists)
  803. class LazyZip(LazyMap):
  804. """
  805. A lazy sequence whose elements are tuples, each containing the i-th
  806. element from each of the argument sequences. The returned list is
  807. truncated in length to the length of the shortest argument sequence. The
  808. tuples are constructed lazily -- i.e., when you read a value from the
  809. list, ``LazyZip`` will calculate that value by forming a tuple from
  810. the i-th element of each of the argument sequences.
  811. ``LazyZip`` is essentially a lazy version of the Python primitive function
  812. ``zip``. In particular, an evaluated LazyZip is equivalent to a zip:
  813. >>> from nltk.util import LazyZip
  814. >>> sequence1, sequence2 = [1, 2, 3], ['a', 'b', 'c']
  815. >>> zip(sequence1, sequence2)
  816. [(1, 'a'), (2, 'b'), (3, 'c')]
  817. >>> list(LazyZip(sequence1, sequence2))
  818. [(1, 'a'), (2, 'b'), (3, 'c')]
  819. >>> sequences = [sequence1, sequence2, [6,7,8,9]]
  820. >>> zip(*sequences) == list(LazyZip(*sequences))
  821. True
  822. Lazy zips can be useful for conserving memory in cases where the argument
  823. sequences are particularly long.
  824. A typical example of a use case for this class is combining long sequences
  825. of gold standard and predicted values in a classification or tagging task
  826. in order to calculate accuracy. By constructing tuples lazily and
  827. avoiding the creation of an additional long sequence, memory usage can be
  828. significantly reduced.
  829. """
  830. def __init__(self, *lists):
  831. """
  832. :param lists: the underlying lists
  833. :type lists: list(list)
  834. """
  835. LazyMap.__init__(self, lambda *elts: elts, *lists)
  836. def iterate_from(self, index):
  837. iterator = LazyMap.iterate_from(self, index)
  838. while index < len(self):
  839. yield iterator.next()
  840. index += 1
  841. return
  842. def __len__(self):
  843. return min(len(lst) for lst in self._lists)
  844. class LazyEnumerate(LazyZip):
  845. """
  846. A lazy sequence whose elements are tuples, each ontaining a count (from
  847. zero) and a value yielded by underlying sequence. ``LazyEnumerate`` is
  848. useful for obtaining an indexed list. The tuples are constructed lazily
  849. -- i.e., when you read a value from the list, ``LazyEnumerate`` will
  850. calculate that value by forming a tuple from the count of the i-th
  851. element and the i-th element of the underlying sequence.
  852. ``LazyEnumerate`` is essentially a lazy version of the Python primitive
  853. function ``enumerate``. In particular, the following two expressions are
  854. equivalent:
  855. >>> from nltk.util import LazyEnumerate
  856. >>> sequence = ['first', 'second', 'third']
  857. >>> list(enumerate(sequence))
  858. [(0, 'first'), (1, 'second'), (2, 'third')]
  859. >>> list(LazyEnumerate(sequence))
  860. [(0, 'first'), (1, 'second'), (2, 'third')]
  861. Lazy enumerations can be useful for conserving memory in cases where the
  862. argument sequences are particularly long.
  863. A typical example of a use case for this class is obtaining an indexed
  864. list for a long sequence of values. By constructing tuples lazily and
  865. avoiding the creation of an additional long sequence, memory usage can be
  866. significantly reduced.
  867. """
  868. def __init__(self, lst):
  869. """
  870. :param lst: the underlying list
  871. :type lst: list
  872. """
  873. LazyZip.__init__(self, xrange(len(lst)), lst)
  874. ######################################################################
  875. # Binary Search in a File
  876. ######################################################################
  877. # inherited from pywordnet, by Oliver Steele
  878. def binary_search_file(file, key, cache={}, cacheDepth=-1):
  879. """
  880. Return the line from the file with first word key.
  881. Searches through a sorted file using the binary search algorithm.
  882. :type file: file
  883. :param file: the file to be searched through.
  884. :type key: str
  885. :param key: the identifier we are searching for.
  886. """
  887. key = key + ' '
  888. keylen = len(key)
  889. start = 0
  890. currentDepth = 0
  891. if hasattr(file, 'name'):
  892. end = os.stat(file.name).st_size - 1
  893. else:
  894. file.seek(0, 2)
  895. end = file.tell() - 1
  896. file.seek(0)
  897. while start < end:
  898. lastState = start, end
  899. middle = (start + end) / 2
  900. if cache.get(middle):
  901. offset, line = cache[middle]
  902. else:
  903. line = ""
  904. while True:
  905. file.seek(max(0, middle - 1))
  906. if middle > 0:
  907. file.readline()
  908. offset = file.tell()
  909. line = file.readline()
  910. if line != "": break
  911. # at EOF; try to find start of the last line
  912. middle = (start + middle)/2
  913. if middle == end -1:
  914. return None
  915. if currentDepth < cacheDepth:
  916. cache[middle] = (offset, line)
  917. if offset > end:
  918. assert end != middle - 1, "infinite loop"
  919. end = middle - 1
  920. elif line[:keylen] == key:
  921. return line
  922. elif line > key:
  923. assert end != middle - 1, "infinite loop"
  924. end = middle - 1
  925. elif line < key:
  926. start = offset + len(line) - 1
  927. currentDepth += 1
  928. thisState = start, end
  929. if lastState == thisState:
  930. # Detects the condition where we're searching past the end
  931. # of the file, which is otherwise difficult to detect
  932. return None
  933. return None
  934. ######################################################################
  935. # Proxy configuration
  936. ######################################################################
  937. def set_proxy(proxy, (user, password)=(None, '')):
  938. """
  939. Set the HTTP proxy for Python to download through.
  940. If ``proxy`` is None then tries to set proxy from environment or system
  941. settings.
  942. :param proxy: The HTTP proxy server to use. For example:
  943. 'http://proxy.example.com:3128/'
  944. :param user: The username to authenticate with. Use None to disable
  945. authentication.
  946. :param password: The password to authenticate with.
  947. """
  948. import urllib
  949. import urllib2
  950. if proxy is None:
  951. # Try and find the system proxy settings
  952. try:
  953. proxy = urllib.getproxies()['http']
  954. except KeyError:
  955. raise ValueError('Could not detect default proxy settings')
  956. # Set up the proxy handler
  957. proxy_handler = urllib2.ProxyHandler({'http': proxy})
  958. opener = urllib2.build_opener(proxy_handler)
  959. if user is not None:
  960. # Set up basic proxy authentication if provided
  961. password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
  962. password_manager.add_password(realm=None, uri=proxy, user=user,
  963. passwd=password)
  964. opener.add_handler(urllib2.ProxyBasicAuthHandler(password_manager))
  965. opener.add_handler(urllib2.ProxyDigestAuthHandler(password_manager))
  966. # Overide the existing url opener
  967. urllib2.install_opener(opener)