I am looking to replace from a large document all high unicode characters, such as accented Es, left and right quotes, etc., with "normal" counterparts in the low range, such as a regular 'E', and straight quotes. I need to perform this on a very large document rather often. I see an example of this in what I think might be perl here: http://www.designmeme.com/mtplugins/lowdown.txt
Is there a fast way of doing this in Python without using s.replace(...).replace(...).replace(...)...? I've tried this on just a few characters to replace and the document stripping became really slow.
EDIT, my version of unutbu's code that doesn't seem to work:
# -*- coding: iso-8859-15 -*-
import unidecode
def ascii_map():
data={}
for num in range(256):
h=num
filename='x{num:02x}'.format(num=num)
try:
mod = __import__('unidecode.'+filename,
fromlist=True)
except ImportError:
pass
else:
for l,val in enumerate(mod.data):
i=h<<8
i+=l
if i >= 0x80:
data[i]=unicode(val)
return data
if __name__=='__main__':
s = u'“fancy“fancy2'
print(s.translate(ascii_map()))
If unicodedata.normalize() as suggested by
~unubtu
doesn't do the trick, for example if you want more control over the mapping, you should look intostr.translate()
along with str.maketrans(), a utility to produce a map table, str.translate is both efficient and convenient for this type of translation.
In Python 2.x and for unicode strings one needs to use unicode.translate() rather than str.translate() and a trick similar to the one shown in the code snippet below, in lieu of maketrans(). (thanks to John Machin for pointing this out!)
These methods are also availble in in Python 3.x see for example the Python 3.1.2 documentation (for some reason I had made a mental note that this may have changed in Python 3.x). Of course under Python 3, all strings are unicode strings, but that's other issue.
Note, as @Mark Tolonen kindly points out, the method above removes some characters like ß‘’“”. If the above code truncates characters that you wish translated, then you may have to use the string's
translate
method to manually fix these problems. Another option is to use unidecode (see J.F. Sebastian's answer).When you have a large unicode string, using its
translate
method will be much much faster than using thereplace
method.Edit:
unidecode
has a more complete mapping of unicode codepoints to ascii. However,unidecode.unidecode
loops through the string character-by-character (in a Python loop), which is slower than using thetranslate
method.The following helper function uses
unidecode
's data files, and thetranslate
method to attain better speed, especially for long strings.In my tests on 1-6 MB text files, using
ascii_map
is about 4-6 times faster thanunidecode.unidecode
.Edit2: Rhubarb, if
# -*- encoding: utf-8 -*-
is causing a SyntaxError, try# -*- encoding: cp1252 -*-
. What encoding to declare depends on what encoding your text editor uses to save the file. Linux tends to use utf-8, and (it seems perhaps) Windows tends to cp1252.I believe that
unicodedata
doesn't work for fancy quotes. You could useUnidecode
in this case:There is no such thing as a "high ascii character". The ASCII character set is limited to ordinal in range(128).
That aside, this is a FAQ. Here's one answer. In general, you should familiarise yourself with str.translate() and unicode.translate() -- very handy for multiple substitutions of single bytes/characters. Beware of answers that mention only the unicodedata.normalize() gimmick; that's just one part of the solution.
Update: The currently-accepted answer blows away characters that don't have a decomposition, as pointed out by Mark Tolonen. There seems to be a lack of knowledge of what
unicode.translate()
is capable of. It CAN translate one character into multiple characters. Here is the output fromhelp(unicode.translate)
:Here's an example:
Here's a table of fix-ups from the solution that I pointed to:
This can be easily extended to cater for the fancy quotes and other non-latin-1 characters found in cp1252 and siblings.
Here's a solution that handles latin-1 characters (based on a 2003 usenet thread):
Some of the mappings aren't perfect e.g. Thorn maps to T rather than Th, but it does a tolerable job.