[Python-de] Encoding von Datei rausbekommen

Michael Weber michael.weber at fh-stralsund.de
Mi Apr 11 14:51:34 CEST 2012


Hallo Thomas,

das werde ich mir doch glatt mal zu Gemüte führen.

> Hallo,
>
> ich verwende folgendes Schnippsel gelegentlich. Für meine Zwecke reicht
> es (latin1 vs utf8). Hier wird aber
> mit Zeichenketten gearbeitet, so dass nicht codecs.open() gearbeitet
> werden kann.
>
> # Attention: Order of encoding_guess_list is import. Example: "latin1"
> always succeeds.
> encoding_guess_list=['utf8', 'latin1']
> def try_unicode(string, errors='strict'):
> if isinstance(string, unicode):
> return string
> assert isinstance(string, str), repr(string)
> for enc in encoding_guess_list:
> try:
> return string.decode(enc, errors)
> except UnicodeError, exc:
> continue
> raise UnicodeError('Failed to convert %r' % string)
> def test_try_unicode():
> for start, should in [
> ('\xfc', u'ü'),
> ('\xc3\xbc', u'ü'),
> ('\xbb', u'\xbb'), # postgres/psycopg2 latin1: RIGHT-POINTING DOUBLE
> ANGLE QUOTATION MARK
> ]:
> result=try_unicode(start, errors='strict')
> if not result==should:
> raise Exception(u'Error: start=%r should=%r result=%r' % (
> start, should, result))
>
>

Grüße und Danke
Michael


Mehr Informationen über die Mailingliste python-de