BVB Source Codes

TextBlob Show mixins.py Source code

Return Download TextBlob: download mixins.py Source code - Download TextBlob Source code - Type:.py
  1. # -*- coding: utf-8 -*-
  2. from __future__ import absolute_import
  3. import sys
  4. from textblob.compat import basestring, implements_to_string, PY2, binary_type
  5.  
  6.  
  7. class ComparableMixin(object):
  8.  
  9.     '''Implements rich operators for an object.'''
  10.  
  11.     def _compare(self, other, method):
  12.         try:
  13.             return method(self._cmpkey(), other._cmpkey())
  14.         except (AttributeError, TypeError):
  15.             # _cmpkey not implemented, or return different type,
  16.             # so I can't compare with "other". Try the reverse comparison
  17.             return NotImplemented
  18.  
  19.     def __lt__(self, other):
  20.         return self._compare(other, lambda s, o: s < o)
  21.  
  22.     def __le__(self, other):
  23.         return self._compare(other, lambda s, o: s <= o)
  24.  
  25.     def __eq__(self, other):
  26.         return self._compare(other, lambda s, o: s == o)
  27.  
  28.     def __ge__(self, other):
  29.         return self._compare(other, lambda s, o: s >= o)
  30.  
  31.     def __gt__(self, other):
  32.         return self._compare(other, lambda s, o: s > o)
  33.  
  34.     def __ne__(self, other):
  35.         return self._compare(other, lambda s, o: s != o)
  36.  
  37.  
  38. class BlobComparableMixin(ComparableMixin):
  39.  
  40.     '''Allow blob objects to be comparable with both strings and blobs.'''
  41.  
  42.     def _compare(self, other, method):
  43.         if isinstance(other, basestring):
  44.             # Just compare with the other string
  45.             return method(self._cmpkey(), other)
  46.         return super(BlobComparableMixin, self)._compare(other, method)
  47.  
  48.  
  49. @implements_to_string
  50. class StringlikeMixin(object):
  51.  
  52.     '''Make blob objects behave like Python strings.
  53.  
  54.    Expects that classes that use this mixin to have a _strkey() method that
  55.    returns the string to apply string methods to. Using _strkey() instead
  56.    of __str__ ensures consistent behavior between Python 2 and 3.
  57.    '''
  58.  
  59.     def __repr__(self):
  60.         '''Returns a string representation for debugging.'''
  61.         class_name = self.__class__.__name__
  62.         text = self.__unicode__().encode("utf-8") if PY2 else str(self)
  63.         ret = '{cls}("{text}")'.format(cls=class_name,
  64.                                         text=text)
  65.         return binary_type(ret) if PY2 else ret
  66.  
  67.     def __str__(self):
  68.         '''Returns a string representation used in print statements
  69.        or str(my_blob).'''
  70.         return self._strkey()
  71.  
  72.     def __len__(self):
  73.         '''Returns the length of the raw text.'''
  74.         return len(self._strkey())
  75.  
  76.     def __iter__(self):
  77.         '''Makes the object iterable as if it were a string,
  78.        iterating through the raw string's characters.
  79.        '''
  80.         return iter(self._strkey())
  81.  
  82.     def __contains__(self, sub):
  83.         '''Implements the `in` keyword like a Python string.'''
  84.         return sub in self._strkey()
  85.  
  86.     def __getitem__(self, index):
  87.         '''Returns a  substring. If index is an integer, returns a Python
  88.        string of a single character. If a range is given, e.g. `blob[3:5]`,
  89.        a new instance of the class is returned.
  90.        '''
  91.         if isinstance(index, int):
  92.             return self._strkey()[index]  # Just return a single character
  93.         else:
  94.             # Return a new blob object
  95.             return self.__class__(self._strkey()[index])
  96.  
  97.     def find(self, sub, start=0, end=sys.maxsize):
  98.         '''Behaves like the built-in str.find() method. Returns an integer,
  99.        the index of the first occurrence of the substring argument sub in the
  100.        sub-string given by [start:end].
  101.        '''
  102.         return self._strkey().find(sub, start, end)
  103.  
  104.     def rfind(self, sub, start=0, end=sys.maxsize):
  105.         '''Behaves like the built-in str.rfind() method. Returns an integer,
  106.        the index of he last (right-most) occurence of the substring argument
  107.        sub in the sub-sequence given by [start:end].
  108.        '''
  109.         return self._strkey().rfind(sub, start, end)
  110.  
  111.     def index(self, sub, start=0, end=sys.maxsize):
  112.         '''Like blob.find() but raise ValueError when the substring
  113.        is not found.
  114.        '''
  115.         return self._strkey().index(sub, start, end)
  116.  
  117.     def rindex(self, sub, start=0, end=sys.maxsize):
  118.         '''Like blob.rfind() but raise ValueError when substring is not
  119.        found.
  120.        '''
  121.         return self._strkey().rindex(sub, start, end)
  122.  
  123.     def startswith(self, prefix, start=0, end=sys.maxsize):
  124.         """Returns True if the blob starts with the given prefix."""
  125.         return self._strkey().startswith(prefix, start, end)
  126.  
  127.     def endswith(self, suffix, start=0, end=sys.maxsize):
  128.         """Returns True if the blob ends with the given suffix."""
  129.         return self._strkey().endswith(suffix, start, end)
  130.  
  131.     # PEP8 aliases
  132.     starts_with = startswith
  133.     ends_with = endswith
  134.  
  135.     def title(self):
  136.         """Returns a blob object with the text in title-case."""
  137.         return self.__class__(self._strkey().title())
  138.  
  139.     def format(self, *args, **kwargs):
  140.         """Perform a string formatting operation, like the built-in
  141.        `str.format(*args, **kwargs)`. Returns a blob object.
  142.        """
  143.         return self.__class__(self._strkey().format(*args, **kwargs))
  144.  
  145.     def split(self, sep=None, maxsplit=sys.maxsize):
  146.         """Behaves like the built-in str.split().
  147.        """
  148.         return self._strkey().split(sep, maxsplit)
  149.  
  150.     def strip(self, chars=None):
  151.         """Behaves like the built-in str.strip([chars]) method. Returns
  152.        an object with leading and trailing whitespace removed.
  153.        """
  154.         return self.__class__(self._strkey().strip(chars))
  155.  
  156.     def upper(self):
  157.         """Like str.upper(), returns new object with all upper-cased characters.
  158.        """
  159.         return self.__class__(self._strkey().upper())
  160.  
  161.     def lower(self):
  162.         """Like str.lower(), returns new object with all lower-cased characters.
  163.        """
  164.         return self.__class__(self._strkey().lower())
  165.  
  166.     def join(self, iterable):
  167.         """Behaves like the built-in `str.join(iterable)` method, except
  168.        returns a blob object.
  169.  
  170.        Returns a blob which is the concatenation of the strings or blobs
  171.        in the iterable.
  172.        """
  173.         return self.__class__(self._strkey().join(iterable))
  174.  
  175.     def replace(self, old, new, count=sys.maxsize):
  176.         """Return a new blob object with all the occurence of `old` replaced
  177.        by `new`.
  178.        """
  179.         return self.__class__(self._strkey().replace(old, new, count))
  180.  
downloadmixins.py Source code - Download TextBlob Source code
Related Source Codes/Software:
monaco-editor - A browser based code editor 2017-01-07
grumpy - Grumpy is a Python to Go source code transcompiler... 2017-01-07
flinux - Foreign LINUX - Run unmodified Linux applications ... 2017-01-07
beeswithmachineguns - A utility for arming (creating) many bees (micro E... 2017-01-07
TopDeepLearning - A list of popular github projects related to deep ... 2017-01-07
yui3 - A library for building richly interactive web appl... 2017-01-07
KineticJS - KineticJS is an HTML5 Canvas JavaScript framework ... 2017-01-07
web-design-standards - Open source UI components and visual style guide f... 2017-01-07
Knuff - The debug application for Apple Push Notification ... 2017-01-07
RoundedImageView - A fast ImageView that supports rounded corners, ov... 2017-01-07
CRYENGINE - CRYENGINE is a powerful real-time game development... 2017-06-11
postal - 2017-06-11
reactide - Reactide is the first dedicated IDE for React web ... 2017-06-11
rkt - rkt is a pod-native container engine for Linux. It... 2017-06-11
uWebSockets - Tiny WebSockets https://for... 2017-06-11
realworld - TodoMVC for the RealWorld - Exemplary fullstack Me... 2017-06-11
goreplay - GoReplay is an open-source tool for capturing and ... 2017-06-10
pyenv - Simple Python version management 2017-06-10
redux-saga - An alternative side effect model for Redux apps ... 2017-06-10
angular-starter - 2017-06-10

 Back to top