I am trying to parse a CSV file containing some data, mostly numeral but with some strings – which I do not know their encoding, but I do know they are in Hebrew.
Eventually I need to know the encoding so I can unicode the strings, print them, and perhaps throw them into a database later on.
I tried using Chardet, which claims the strings are Windows-1255 (cp1255) but trying to do print someString.decode('cp1255') yields the notorious error:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-4: ordinal not in range(128)
I tried every other encoding possible, to no avail. Also, the file is absolutely valid since I can open the CSV in Excel and I see the correct data.
Any idea how I can properly decode these strings?
EDIT: here is an example. One of the strings looks like this (first five letters of the Hebrew alphabet):
print repr(sampleString)
#prints:
'\xe0\xe1\xe2\xe3\xe4'
(using Python 2.6.2)
This is what’s happening:
sampleString.decode("cp1255")decodes (decode==bytes -> unicode string) the byte string to a unicode stringprint sampleString.decode("cp1255")attempts to print the unicode string to stdout. Print has to encode the unicode string to do that (encode==unicode string -> bytes). The error that you’re seeing means that the python print statement cannot write the given unicode string to the console’s encoding.sys.stdout.encodingis the terminal’s encoding.So the problem is that your console does not support these characters. You should be able to tweak the console to use another encoding. The details on how to do that depends on your OS and terminal program.
Another approach would be to manually specify the encoding to use:
See also:
A simple test program you can experiment with:
On my utf-8 terminal:
The error messages for latin-1 and ascii means that the unicode characters in the string cannot be represented in these encodings.
Notice the last two. I encode the unicode string to the cp424 and iso8859_8 encodings (two of the encodings listed on http://docs.python.org/library/codecs.html#standard-encodings that supports hebrew characters). I get no exception using these encodings, since the hebrew unicode characters have a representation in the encodings.
But my utf-8 terminal gets very confused when it receives bytes in a different encoding than utf-8.
In the first case (cp424), my UTF-8 terminal displays ABCDE, meaning that the utf-8 representation of A corresponds to the cp424 representation of ה, i.e. the byte value 65 means A in utf-8 and ה in cp424.
The
encodemethod has an optional string argument you can use to specify what should happen when the encoding cannot represent a character (documentation). The supported strategies are strict (the default), ignore, replace, xmlcharref and backslashreplace. You can even add your own custom strategies.Another test program (I print with quotes around the string to better show how ignore behaves):
The results: