views:

1828

answers:

12

Say I have a string that looks like this:

str = "The &yquick &cbrown &bfox &Yjumps over the &ulazy dog"

You'll notice a lot of locations in the string where there is an ampersand, followed by a character (such as "&y" and "&c"). I need to replace these characters with an appropriate value that I have in a dictionary, like so:

dict = {"&y":"\033[0;30m",
        "&c":"\033[0;31m",
        "&b":"\033[0;32m",
        "&Y":"\033[0;33m",
        "&u":"\033[0;34m"}

What is the fastest way to do this? I could manually find all the ampersands, then loop through the dictionary to change them, but that seems slow. Doing a bunch of regex replaces seems slow as well (I will have a dictionary of about 30-40 pairs in my actual code).

Any suggestions are appreciated, thanks.

Edit:

As has been pointed out in comments throught this question, my dictionary is defined before runtime, and will never change during the course of the applications life cycle. It is a list of ANSI escape sequences, and will have about 40 items in it. My average string length to compare against will be about 500 characters, but there will be ones that are up to 5000 characters (although, these will be rare). I am also using Python 2.6 currently.

Edit #2 I accepted Tor Valamos answer as the correct one, as it not only gave a valid solution (although it wasn't the best solution), but took all others into account and did a tremendous amount of work to compare all of them. That answer is one of the best, most helpful answers I have ever come across on StackOverflow. Kudos to you.

+12  A: 
mydict = {"&y":"\033[0;30m",
          "&c":"\033[0;31m",
          "&b":"\033[0;32m",
          "&Y":"\033[0;33m",
          "&u":"\033[0;34m"}
mystr = "The &yquick &cbrown &bfox &Yjumps over the &ulazy dog"

for k, v in mydict.iteritems():
    mystr = mystr.replace(k, v)

print mystr
The ←[0;30mquick ←[0;31mbrown ←[0;32mfox ←[0;33mjumps over the ←[0;34mlazy dog

I took the liberty of comparing a few solutions:

mydict = dict([('&' + chr(i), str(i)) for i in list(range(65, 91)) + list(range(97, 123))])

# random inserts between keys
from random import randint
rawstr = ''.join(mydict.keys())
mystr = ''
for i in range(0, len(rawstr), 2):
    mystr += chr(randint(65,91)) * randint(0,20) # insert between 0 and 20 chars

from time import time

# How many times to run each solution
rep = 10000

print 'Running %d times with string length %d and ' \
      'random inserts of lengths 0-20' % (rep, len(mystr))

# My solution
t = time()
for x in range(rep):
    for k, v in mydict.items():
        mystr.replace(k, v)
    #print(mystr)
print '%-30s' % 'Tor fixed & variable dict', time()-t

from re import sub, compile, escape

# Peter Hansen
t = time()
for x in range(rep):
    sub(r'(&[a-zA-Z])', r'%(\1)s', mystr) % mydict
print '%-30s' % 'Peter fixed & variable dict', time()-t

# Claudiu
def multiple_replace(dict, text): 
    # Create a regular expression  from the dictionary keys
    regex = compile("(%s)" % "|".join(map(escape, dict.keys())))

    # For each match, look-up corresponding value in dictionary
    return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)

t = time()
for x in range(rep):
    multiple_replace(mydict, mystr)
print '%-30s' % 'Claudio variable dict', time()-t

# Claudiu - Precompiled
regex = compile("(%s)" % "|".join(map(escape, mydict.keys())))

t = time()
for x in range(rep):
    regex.sub(lambda mo: mydict[mo.string[mo.start():mo.end()]], mystr)
print '%-30s' % 'Claudio fixed dict', time()-t

# Andrew Y - variable dict
def mysubst(somestr, somedict):
  subs = somestr.split("&")
  return subs[0] + "".join(map(lambda arg: somedict["&" + arg[0:1]] + arg[1:], subs[1:]))

t = time()
for x in range(rep):
    mysubst(mystr, mydict)
print '%-30s' % 'Andrew Y variable dict', time()-t

# Andrew Y - fixed
def repl(s):
  return mydict["&"+s[0:1]] + s[1:]

t = time()
for x in range(rep):
    subs = mystr.split("&")
    res = subs[0] + "".join(map(repl, subs[1:]))
print '%-30s' % 'Andrew Y fixed dict', time()-t

Results in Python 2.6

Running 10000 times with string length 490 and random inserts of lengths 0-20
Tor fixed & variable dict      1.04699993134
Peter fixed & variable dict    0.218999862671
Claudio variable dict          2.48400020599
Claudio fixed dict             0.0940001010895
Andrew Y variable dict         0.0309998989105
Andrew Y fixed dict            0.0310001373291

Both claudiu's and andrew's solutions kept going into 0, so I had to increase it to 10 000 runs.

I ran it in Python 3 (because of unicode) with replacements of chars from 39 to 1024 (38 is ampersand, so I didn't wanna include it). String length up to 10.000 including about 980 replacements with variable random inserts of length 0-20. The unicode values from 39 to 1024 causes characters of both 1 and 2 bytes length, which could affect some solutions.

mydict = dict([('&' + chr(i), str(i)) for i in range(39,1024)])

# random inserts between keys
from random import randint
rawstr = ''.join(mydict.keys())
mystr = ''
for i in range(0, len(rawstr), 2):
    mystr += chr(randint(65,91)) * randint(0,20) # insert between 0 and 20 chars

from time import time

# How many times to run each solution
rep = 10000

print('Running %d times with string length %d and ' \
      'random inserts of lengths 0-20' % (rep, len(mystr)))

# Tor Valamo - too long
#t = time()
#for x in range(rep):
#    for k, v in mydict.items():
#        mystr.replace(k, v)
#print('%-30s' % 'Tor fixed & variable dict', time()-t)

from re import sub, compile, escape

# Peter Hansen
t = time()
for x in range(rep):
    sub(r'(&[a-zA-Z])', r'%(\1)s', mystr) % mydict
print('%-30s' % 'Peter fixed & variable dict', time()-t)

# Peter 2
def dictsub(m):
    return mydict[m.group()]

t = time()
for x in range(rep):
    sub(r'(&[a-zA-Z])', dictsub, mystr)
print('%-30s' % 'Peter fixed dict', time()-t)

# Claudiu - too long
#def multiple_replace(dict, text): 
#    # Create a regular expression  from the dictionary keys
#    regex = compile("(%s)" % "|".join(map(escape, dict.keys())))
#
#    # For each match, look-up corresponding value in dictionary
#    return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
#
#t = time()
#for x in range(rep):
#    multiple_replace(mydict, mystr)
#print('%-30s' % 'Claudio variable dict', time()-t)

# Claudiu - Precompiled
regex = compile("(%s)" % "|".join(map(escape, mydict.keys())))

t = time()
for x in range(rep):
    regex.sub(lambda mo: mydict[mo.string[mo.start():mo.end()]], mystr)
print('%-30s' % 'Claudio fixed dict', time()-t)

# Separate setup for Andrew and gnibbler optimized dict
mydict = dict((k[1], v) for k, v in mydict.items())

# Andrew Y - variable dict
def mysubst(somestr, somedict):
  subs = somestr.split("&")
  return subs[0] + "".join(map(lambda arg: somedict[arg[0:1]] + arg[1:], subs[1:]))

def mysubst2(somestr, somedict):
  subs = somestr.split("&")
  return subs[0].join(map(lambda arg: somedict[arg[0:1]] + arg[1:], subs[1:]))

t = time()
for x in range(rep):
    mysubst(mystr, mydict)
print('%-30s' % 'Andrew Y variable dict', time()-t)
t = time()
for x in range(rep):
    mysubst2(mystr, mydict)
print('%-30s' % 'Andrew Y variable dict 2', time()-t)

# Andrew Y - fixed
def repl(s):
  return mydict[s[0:1]] + s[1:]

t = time()
for x in range(rep):
    subs = mystr.split("&")
    res = subs[0] + "".join(map(repl, subs[1:]))
print('%-30s' % 'Andrew Y fixed dict', time()-t)

# gnibbler
t = time()
for x in range(rep):
    myparts = mystr.split("&")
    myparts[1:]=[mydict[x[0]]+x[1:] for x in myparts[1:]]
    "".join(myparts)
print('%-30s' % 'gnibbler fixed & variable dict', time()-t)

Results:

Running 10000 times with string length 9491 and random inserts of lengths 0-20
Tor fixed & variable dict      0.0 # disqualified 329 secs
Peter fixed & variable dict    2.07799983025
Peter fixed dict               1.53100013733 
Claudio variable dict          0.0 # disqualified, 37 secs
Claudio fixed dict             1.5
Andrew Y variable dict         0.578000068665
Andrew Y variable dict 2       0.56299996376
Andrew Y fixed dict            0.56200003624
gnibbler fixed & variable dict 0.530999898911

(** Note that gnibbler's code uses a different dict, where keys don't have the '&' included. Andrew's code also uses this alternate dict, but it didn't make much of a difference, maybe just 0.01x speedup.)

Tor Valamo
This is straightforward and probably faster than regex unless the real replacement dict is much larger than 5 elements
gnibbler
gnibbler: My actual dict is going to be about 40 elements.
Mike Trpcic
@Mike, you would have to test to be sure, but regex really are a lot slower than simple replace. I've posted an answer that uses split/join will be interesting to see which approach is better under various conditions
gnibbler
You're not being very fair to Claudiu. First, you're calling his as a function, and function call overhead isn't ignorable in Python. Second, his compilation step would not be done each time, but once at program startup.
Peter Hansen
@Tor, you're having enough fun with this: make sure you upvote Mike's question! :-)
Peter Hansen
@Peter - You're assuming the dictionary is the same for each call, which it may not be. Therefore I'm compiling it for each run. But yeah I'll add a notice about that being the cause of it.
Tor Valamo
@Tor, if you look at what the code is doing, it's inserting ANSI escape sequences for printing things like bold, underline, etc. Those codes are almost certainly pre-defined and unchanging for the OP, so I think it's a good bet you would have a static dict and compile at startup. I could be wrong.
Peter Hansen
If you run my answer correctly: regex = compile("(%s)" % "|".join(map(escape, mydict.keys())))t = time()for x in range(rep): regex.sub(lambda mo: mydict[mo.string[mo.start():mo.end()]], mystr)print(time()-t)Then, for 10000 runs, the numbers I get are:0.3751.281000137330.593999862671So yours is still faster, but mine is much closer.
Claudiu
@Andrew - I timed yours to half the speed of mine, but yours is assuming the the dictionary is consistent, which may not always be the case. But if it is, you're winning.
Tor Valamo
Peter is correct. I will have a predfined dictionary of ANSI escape sequences (for foreground, background, underlining, etc). This list will never change during runtime, so one compile is perfectly sufficient.
Mike Trpcic
@Claudiu - Then your also assuming that the dict is constant, which is ok, but I'll have to differentiate between that.
Tor Valamo
I would love to see an updated benchmark with these new revelations taken into account, as well as some more of the alternatives.
Mike Trpcic
@Tor: actuallymy initial speedup of 40x was due to a stupid typo, with revised test my runtime is about 2/3 of yours - though I did uncomment the print(mystr) statement in your example - and it prints the original string ? I do not code python much, so, not sure if it's me doing something wrong or indeed there is a bug somewhere
Andrew Y
I updated the post with new benchmarks including Andrew's, and differing between fixed and variable dicts.
Tor Valamo
Tor you are truly a master of your craft. I applaud your dedication to helping me with this. Thank you.
Mike Trpcic
@Tor, Mike has said in another comment that his strings may be quite a bit larger ("most... under 500"). Could you try a larger string too, maybe like what you have but with a dozen or so non-code characters between each pair of codes? This may differentiate the solutions more (yours probably getting the advantage).
Peter Hansen
If you read the edits to my post, I've mentioned that most strings will be under 500 characters, but there will be some that are as large as 5000.
Mike Trpcic
@Tor: I've added the variant which wraps the same logic into the function that takes the string to be processed and dictionary as a parameter. Somewhere in the middle between my previous result and yours, it seems.
Andrew Y
I updated with new benchmarks of strings with randoms inserts. Dramatic change in results!
Tor Valamo
Also updated with Andrew's latest, who now beats everybody both on variable and fixed dicts.
Tor Valamo
It seems that Andrew Y's solution is consistently at the top of the list.
Mike Trpcic
@Mike: we should test mine on long strings with a lot of characters to be replaced. I wonder if it will become more problematic then.
Andrew Y
@Andrew, @Peter, @Claudiu - Now tested with A LOT of inserts on LONG strings of unicode in python 3.
Tor Valamo
Andrew Y is still kickin' it on top.
Mike Trpcic
@Tor: I removed the extra concatenation in the "variable" example - see my edit2. This should shave off one more tiny bit, according to my tests :-)
Andrew Y
Peter's alternate solution was tested (fixed dict) and slightly slower (0.01 times) than Claudiu's fixed dict solution.
Tor Valamo
@Andrew, yes, slightly faster, however you're so far on top I'm done editing my post for today :P
Tor Valamo
@Tor: indeed, time to sleep for me as well. Thanks for oding this, it was fun! :)
Andrew Y
I added it just for completeness, but just the results, not the code. My own solution in this test was so slow that I'm still laughing.
Tor Valamo
Thanks to everyone who helped!
Mike Trpcic
gnibbler
@gnibbler, yours is now the fastest.
Tor Valamo
what's the disqualified stuff for?
Claudiu
Took too long to run. See the seconds behind. So I only ran it once and never again.
Tor Valamo
+1  A: 

Not sure about the speed of this solution either, but you could just loop through your dictionary and repeatedly call the built-in

str.replace(old, new)

This might perform decently well if the original string isn't too long, but it would obviously suffer as the string got longer.

Michael Patterson
actually it doesn't suffer from the string length it suffers from the dict length.
Tor Valamo
Interesting... the reason I thought the string length would be more important was because it only loops through the dictionary once but it searches through the string repeatedly. I understand that both will impact the speed, but why does it suffer more from the dict length? (not questioning that you're right, just wondering why?)
Michael Patterson
Because you call the replace once per dict item, so the more dict items the more calls. If the string is longer it wouldn't affect it as much. But it doesn't matter too much anyways, if you see my answer with the benchmarks. :P
Tor Valamo
Right, I was saying compared to other methods it would suffer due to the string length, because every method would have to loop through the entire dictionary, but not every method would have to search through the string repeatedly. However, you're right that it doesn't really matter, just curious. :-p
Michael Patterson
@Michael, the actual reason it isn't as scalable is merely because the string replacement is a loop in pure C, while the dictionary loop is a loop in Python. Where performance matters, in Python, you generally don't want to do lots of Python operations inside Python loops.
Peter Hansen
+2  A: 

If you really want to dig into the topic take a look at this: http://en.wikipedia.org/wiki/Aho-Corasick%5Falgorithm

The obvious solution by iterating over the dictionary and replacing each element in the string takes O(n*m) time, where n is the size of the dictionary, m is the length of the string.

Whereas the Aho-Corasick-Algorithm finds all entries of the dictionary in O(n+m+f) where f is the number of found elements.

Wolfgang Plaschg
+1. For this current problem it seems a bit like overkill for an occasional string replacement though. :P
Tor Valamo
+2  A: 

This seems like it does what you want - multiple string replace at once using RegExps. Here is the relevant code:

def multiple_replace(dict, text): 
    # Create a regular expression  from the dictionary keys
    regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))

    # For each match, look-up corresponding value in dictionary
    return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)

print multiple_replace(dict, str)
Claudiu
already modified. not sure if this code is faster than doing the loop itself; it does have an extra function call for each replacement. will have to time it for that.
Claudiu
Yikes, this would become terribly expensive for any large dictionary and large text.
charstar
My dictionary will have about 40 entries in it, and most of my strings will be under 500 characters. How expensive would this be compared to a looping str.replace() or the suggestion by Peter Hanson?
Mike Trpcic
I benchmarked this in my answer, if you're interested.
Tor Valamo
+10  A: 
Peter Hansen
This has a problem though... if the string contains a match that isn't in the dictionary...
Tor Valamo
The OP didn't specify that he required bullet-proofing. He might say "it's guaranteed that all sequences found in the string are in the dictionary". If every answer without perfect error handling were deleted from StackOverflow, there'd be only a handful left...
Peter Hansen
It's not just about error handling, but the fact that in this will fail completely on the smallest error. I see your second alternative handles this though, with the default return value.
Tor Valamo
Sometimes I very much want code that "fails completely on the smallest error". If it did not, I wouldn't find the problem in the *other* part of my program which was inserting the ampserand escape sequences in the first place. Of course, my unit tests for that other piece tell me it generates only those patterns covered by the dictionary shown, so I know I don't need the redundant error handling that you're talking about adding to my nice clean program, burdening me with extra maintenance overhead. (As you can see, there are times when some people would consider error handling unnecessary.)
Peter Hansen
See my answer for a benchmark, by the way. :)
Tor Valamo
I would be using `lambda m: dict[m.group()]` for this (but I would also abstract this functionality into it's own function).
Chris Lutz
@Chris, I consider lambda mostly a way of obfuscating code by encouraging one to pack more of it onto one line, where a nice separate named function is more readable. To each his own. I'm sure we'd all package this whole thing as its own function in real code though.
Peter Hansen
I've been trying to get your solution working (using the callback that calls dict.get(m.group(), '??'), but I keep receiving the following error: "exceptions.TypeError: descriptor 'get' requires a 'dict' object but received a 'str'". Any suggestions as to why? Platform is Python 2.6.
Mike Trpcic
I'm on Python 2.6 as well so it will work. Sounds like you're using the variable name "dict" instead of "mydict" or "d" or whatever. In your case, it's the dictionary class from the builtins, not a name you've assigned something to. If you make sure not to shadow builtin names (remove any use of "dict", "str" etc as variable names) your problems should vanish. Otherwise please post code and we can fix it.
Peter Hansen
Also, you should probably use the technique in my updated answer labelled "Peter 2" but including the earlier part where I build "charset" dynamically from the dictionary. That way you can avoid the get() call and the '??' argument entirely, making it faster and simpler yet still robust.
Peter Hansen
@Mike, the specific error would come because you're mixing two naming conventions. Your original code used "dict" for the variable name, so that's what my code sample used. However the "dict" in that "dict.get" must be whatever the dictionary *variable* is named. You've got it named something else now (mydict?) so the code isn't working at the moment. In the updated test code, the only use of "dict" is the builtin name, so try using the code from there and make sure your original variables are not "str" and "dict" any more.
Peter Hansen
+5  A: 

If the number of keys in the list is large, and the number of the occurences in the string is low (and mostly zero), then you could iterate over the occurences of the ampersands in the string, and use the dictionary keyed by the first character of the substrings. I don't code often in python so the style might be a bit off, but here is my take at it:

str = "The &yquick &cbrown &bfox &Yjumps over the &ulazy dog"

dict = {"&y":"\033[0;30m",
        "&c":"\033[0;31m",
        "&b":"\033[0;32m",
        "&Y":"\033[0;33m",
        "&u":"\033[0;34m"}

def rep(s):
  return dict["&"+s[0:1]] + s[1:]

subs = str.split("&")
res = subs[0] + "".join(map(rep, subs[1:]))

print res

Of course there is a question what happens when there is an ampersand that is coming from the string itself, you would need to escape it in some way before feeding through this process, and then unescape after this process.

Of course, as is pretty much usual with the performance issues, timing the various approaches on your typical (and also worst-case) dataset and comparing them is a good thing to do.

EDIT: place it into a separate function to work with arbitrary dictionary:

def mysubst(somestr, somedict):
  subs = somestr.split("&")
  return subs[0] + "".join(map(lambda arg: somedict["&" + arg[0:1]] + arg[1:], subs[1:]))

EDIT2: get rid of an unneeded concatenation, seems to still be a bit faster than the previous on many iterations.

def mysubst(somestr, somedict):
  subs = somestr.split("&")
  return subs[0].join(map(lambda arg: somedict["&" + arg[0:1]] + arg[1:], subs[1:]))
Andrew Y
gnibbler
Tor Valamo
@Tor: I doublechecked - and am I right that in the latest test code there are no ampersands at all ? then gnibbler and my code would win, indeed. But we should debug the test suite a bit better tomorrow, imho.
Andrew Y
I'll post my python 3 test code which uses unicode chars and a HUGE dictionary. It puts the solutions under extreme workloads (at least on 10.000 runs :P). But you could come up with better dictionaries too, such as variable length, though that would void most of the solutions, except a few.
Tor Valamo
@Tor: looking forward :) @gnibbler: seems like getting rid of the concat does not make much difference between our scenarios, which is interesting. I think the difference between yours and mine is because of the map/lambda overhead in mine ? (else they are equivalent, it seems).
Andrew Y
@Andrew Y, only now did I noticed your comment about "I doublechecked". I believe you're right, Tor's test code was not using representative inputs. My updated answer includes better inputs, but your code fails on it, probably because it doesn't handle ampsersand sequences that are *not* in the dictionary.
Peter Hansen
@Peter: yes, it throws the exception for the sequences that are not in the dictionary. I wrote in the beginning that the standalone ampersands would need to be escaped before running.
Andrew Y
A: 
>>> a=[]
>>> str = "The &yquick &cbrown &bfox &Yjumps over the &ulazy dog"
>>> d={"&y":"\033[0;30m",                                                              
... "&c":"\033[0;31m",                                                                 
... "&b":"\033[0;32m",                                                                 
... "&Y":"\033[0;33m",                                                                 
... "&u":"\033[0;34m"}     
>>> for item in str.split():
...  if item[:2] in d:
...    a.append(d[item[:2]]+item[2:])
...  else: a.append(item)
>>> print ' '.join(a)
This will only work if there is always a space before the ampersand
gnibbler
i don't want to assume too much. since OP provided samples, i will work with that sample.
+2  A: 

A general solution for defining replacement rules is to use regex substitution using a function to provide the map (see re.sub()).

import re

str = "The &yquick &cbrown &bfox &Yjumps over the &ulazy dog"

dict = {"&y":"\033[0;30m",
        "&c":"\033[0;31m",
        "&b":"\033[0;32m",
        "&Y":"\033[0;33m",
        "&u":"\033[0;34m"}

def programmaticReplacement( match ):
    return dict[ match.group( 1 ) ]

colorstring = re.sub( '(\&.)', programmaticReplacement, str )

This is particularly nice for non-trivial substitutions (e.g anything requiring mathmatical operations to create the substitute).

charstar
+1  A: 

The problem with doing this mass replace in Python is immutability of the strings: every time you will replace one item in the string then entire new string will be reallocated again and again from the heap.

So if you want the fastest solution you either need to use mutable container (e.g. list), or write this machinery in the plain C (or better in Pyrex or Cython). In any case I'd suggest to write simple parser based on simple finite-state machine, and feed symbols of your string one by one.

Suggested solutions based on regexps working in similar way, because regexp working using fsm behind the scene.

bialix
+3  A: 

Here is a version using split/join

mydict = {"y":"\033[0;30m",
          "c":"\033[0;31m",
          "b":"\033[0;32m",
          "Y":"\033[0;33m",
          "u":"\033[0;34m"}
mystr = "The &yquick &cbrown &bfox &Yjumps over the &ulazy dog"

myparts = mystr.split("&")
myparts[1:]=[mydict[x[0]]+x[1:] for x in myparts[1:]]
print "".join(myparts)

In case there are ampersands with invalid codes you can use this to preserve them

myparts[1:]=[mydict.get(x[0],"&"+x[0])+x[1:] for x in myparts[1:]]

Peter Hansen pointed out that this fails when there is double ampersand. In that case use this version

mystr = "The &yquick &cbrown &bfox &Yjumps over the &&ulazy dog"
myparts = mystr.split("&")
myparts[1:]=[mydict.get(x[:1],"&"+x[:1])+x[1:] for x in myparts[1:]]
print "".join(myparts)
gnibbler
Andrew Y
gnibbler
Tor Valamo
I ran it, with the heavy duty test, and yours is faster than Andrew's...
Tor Valamo
@gnibbler: ah yes. I used the original data. Sorry, indeed.
Andrew Y
I believe this fails in the case of double ampsersands.
Peter Hansen
gnibbler
Peter Hansen
+1  A: 

Since someone mentioned using a simple parser, I thought I'd cook one up using pyparsing. By using pyparsing's transformString method, pyparsing internally scans through the source string, and builds a list of the matching text and intervening text. When all is done, transformString then ''.join's this list, so there is no performance problem in building up strings by increments. (The parse action defined for ANSIreplacer does the conversion from the matched &_ characters to the desired escape sequence, and replaces the matched text with the output of the parse action. Since only matching sequences will satisfy the parser expression, there is no need for the parse action to handle undefined &_ sequences.)

The FollowedBy('&') is not strictly necessary, but it shortcuts the parsing process by verifying that the parser is actually positioned at an ampersand before doing the more expensive checking of all of the markup options.

from pyparsing import FollowedBy, oneOf

escLookup = {"&y":"\033[0;30m",
            "&c":"\033[0;31m",
            "&b":"\033[0;32m",
            "&Y":"\033[0;33m",
            "&u":"\033[0;34m"}

# make a single expression that will look for a leading '&', then try to 
# match each of the escape expressions
ANSIreplacer = FollowedBy('&') + oneOf(escLookup.keys())

# add a parse action that will replace the matched text with the 
# corresponding ANSI sequence
ANSIreplacer.setParseAction(lambda toks: escLookup[toks[0]])

# now use the replacer to transform the test string; throw in some extra
# ampersands to show what happens with non-matching sequences
src = "The &yquick &cbrown &bfox &Yjumps over the &ulazy dog & &Zjumps back"
out = ANSIreplacer.transformString(src)
print repr(out)

Prints:

'The \x1b[0;30mquick \x1b[0;31mbrown \x1b[0;32mfox \x1b[0;33mjumps over 
 the \x1b[0;34mlazy dog & &Zjumps back'

This will certainly not win any performance contests, but if your markup starts to get more complicated, then having a parser foundation will make it easier to extend.

Paul McGuire
Paul, at least it works on real input (verified using the test code in my updated answer), where some others do not. Unfortunately it is very slow compared to the others: it takes 282 times longer than the re.sub solution.
Peter Hansen
+4  A: 

Here is the C Extensions Approach for python

const char *dvals[]={
    //"0-64
    "","","","","","","","","","",
    "","","","","","","","","","",
    "","","","","","","","","","",
    "","","","","","","","","","",
    "","","","","","","","","","",
    "","","","","","","","","","",
    "","","","","",
    //A-Z
    "","","","","",
    "","","","","",
    "","","","","",
    "","","","","",
    "","","","","33",
    "",
    //
    "","","","","","",
    //a-z
    "","32","31","","",
    "","","","","",
    "","","","","",
    "","","","","",
    "34","","","","30",
    ""
};

int dsub(char*d,char*s){
    char *ofs=d;
    do{
     if(*s=='&' && s[1]<='z' && *dvals[s[1]]){

      //\033[0;
      *d++='\\',*d++='0',*d++='3',*d++='3',*d++='[',*d++='0',*d++=';';

      //consider as fixed 2 digits
      *d++=dvals[s[1]][0];
      *d++=dvals[s[1]][1];

      *d++='m';

      s++; //skip

     //non &,invalid, unused (&) ampersand sequences will go here.
     }else *d++=*s;

    }while(*s++);

    return d-ofs-1;
}

Python codes I have tested

from mylib import *
import time

start=time.time()

instr="The &yquick &cbrown &bfox &Yjumps over the &ulazy dog, skip &Unknown.\n"*100000
x=dsub(instr)

end=time.time()

print "time taken",end-start,",input str length",len(x)
print "first few lines"
print x[:1100]

Results

time taken 0.140000104904 ,input str length 11000000
first few lines
The \033[0;30mquick \033[0;31mbrown \033[0;32mfox \033[0;33mjumps over the \033[0;34mlazy dog, skip &Unknown.
The \033[0;30mquick \033[0;31mbrown \033[0;32mfox \033[0;33mjumps over the \033[0;34mlazy dog, skip &Unknown.
The \033[0;30mquick \033[0;31mbrown \033[0;32mfox \033[0;33mjumps over the \033[0;34mlazy dog, skip &Unknown.
The \033[0;30mquick \033[0;31mbrown \033[0;32mfox \033[0;33mjumps over the \033[0;34mlazy dog, skip &Unknown.
The \033[0;30mquick \033[0;31mbrown \033[0;32mfox \033[0;33mjumps over the \033[0;34mlazy dog, skip &Unknown.
The \033[0;30mquick \033[0;31mbrown \033[0;32mfox \033[0;33mjumps over the \033[0;34mlazy dog, skip &Unknown.
The \033[0;30mquick \033[0;31mbrown \033[0;32mfox \033[0;33mjumps over the \033[0;34mlazy dog, skip &Unknown.
The \033[0;30mquick \033[0;31mbrown \033[0;32mfox \033[0;33mjumps over the \033[0;34mlazy dog, skip &Unknown.
The \033[0;30mquick \033[0;31mbrown \033[0;32mfox \033[0;33mjumps over the \033[0;34mlazy dog, skip &Unknown.
The \033[0;30mquick \033[0;31mbrown \033[0;32mfox \033[0;33mjumps over the \033[0;34mlazy dog, skip &Unknown.

Its suppose to able to run at O(n), and Only took 160 ms (avg) for 11 MB string in My Mobile Celeron 1.6 GHz PC

It will also skip unknown characters as is, for example &Unknown will return as is

Let me know If you have any problem with compiling, bugs, etc...

S.Mark
Can you benchmark it using my test? It would seem that if you wanted to change the dictionary you'd have to do a lot of work...
Tor Valamo
I have added some benchmark codes
S.Mark
I see a bug, it's not replacing the character, only the ampersand.
Tor Valamo
Could you tell me which part of the code? `*d++=dvals[s[1]][0];*d++=dvals[s[1]][1];` supposed to do that replacing actually.
S.Mark
The output says so :P
Tor Valamo
The 30m**y**quick. That y shouldn't be there.
Tor Valamo
I have overlooked, right, corrected, thanks a lot.
S.Mark
for dictionary changes, only need to update dvals, and recompile it, only the compiling will be extra step.
S.Mark