def NarrowText(self, text, encoding):
    """ Narrow a piece of arbitrary text """
    if type(text) != types.UnicodeType:
      return text

    # Try the passed in preference
    if encoding:
      try:
        result = text.encode(encoding)
        if not encoding in self._learned:
          self._learned.append(encoding)
        return result
      except UnicodeError:
        pass
      except LookupError:
        output.Warn('Unknown encoding: %s' % encoding)

    # Try the user preference
    if self._user:
      try:
        return text.encode(self._user)
      except UnicodeError:
        pass
      except LookupError:
        temp = self._user
        self._user = None
        output.Warn('Unknown default_encoding: %s' % temp)

    # Look through learned defaults, knock any failing ones out of the list
    while self._learned:
      try:
        return text.encode(self._learned[0])
      except:
        del self._learned[0]

    # When all other defaults are exhausted, use UTF-8
    try:
      return text.encode(ENC_UTF8)
    except UnicodeError:
      pass

    # Something is seriously wrong if we get to here
    return text.encode(ENC_ASCII, 'ignore')
  #end def NarrowText
dataset/ETHPy150Open benoitc/gunicorn/docs/sitemap_gen.py/Encoder.NarrowText/original