Python - regex and unicode issues

Hi, I have a problem in python. I am trying to explain my problem with an example.

I have this line:

>>> string = 'ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ' >>> print string ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂà 

and I want, for example, to replace charachters other than Ñ, Ã, ï with ""

I tried:

 >>> rePat = re.compile('[^ÑÃï]',re.UNICODE) >>> print rePat.sub("",string)  Ñ                             ï                   Ã 

I got it. I think this is because this type of character in python is represented by two positions in the vector: for example, \ xc3 \ x91 = Ñ. To do this, when I do the regex expression, all \ xc3 are not replaced. How can I make this type sub ?????

Thanks Franco

+4
source share
1 answer

You need to make sure your strings are unicode strings, not string strings (simple strings are like arrays of bytes).

Example:

 >>> string = 'ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ' >>> type(string) <type 'str'> # do this instead: # (note the u in front of the ', this marks the character sequence as a unicode literal) >>> string = u'\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\xc0\xc1\xc2\xc3' # or: >>> string = 'ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ'.decode('utf-8') # ... but be aware that the latter will only work if the terminal (or source file) has utf-8 encoding # ... it is a best practice to use the \xNN form in unicode literals, as in the first example >>> type(string) <type 'unicode'> >>> print string ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂà >>> rePat = re.compile(u'[^\xc3\x91\xc3\x83\xc3\xaf]',re.UNICODE) >>> print rePat.sub("", string) à 

When reading from a file, string = open('filename.txt').read() Read string = open('filename.txt').read() reads a sequence of bytes.

To get the unicode content, do: string = unicode(open('filename.txt').read(), 'encoding') . Or: string = open('filename.txt').read().decode('encoding') .

The codecs module can instantly decode Unicode streams (e.g. files).

Do a google search for python unicode . Managing Python's Unicode is a bit hard to understand; it pays to read it.

I live by this rule: "The software should only work with Unicode strings inside, converting it to a specific encoding at the output." (from http://www.amk.ca/python/howto/unicode )

I also recommend: http://www.joelonsoftware.com/articles/Unicode.html

+14
source

All Articles