'Narrow a piece of arbitrary text'

def NarrowText(self, text, encoding):

    if (type(text) != types.UnicodeType):
        return text
    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))
    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))
    while self._learned:
        try:
            return text.encode(self._learned[0])
        except:
            del self._learned[0]
    try:
        return text.encode(ENC_UTF8)
    except UnicodeError:
        pass
    return text.encode(ENC_ASCII, 'ignore')
