Luhmann wrote:
Hi folks,

I'm trying to do something like this:

evildict= {'good' : 'bad' , 'love' : 'hate' , 'God': 'Satan'}

def make_evil(text)
...        for a in evildict:
...              text=text.replace(a, evildict[a])
...              return text
This works fine, but it soon gets too slow as the size of text and dictionary 
begin to grow.
Can you guys suggest me a way to make it faster?

You're basically moving slowly towards a templating mechanism.
Depends on just how fancy you want to get. In short, to
do this kind of thing, the steps are:

1) Roll-your-own dict solution [what you've done]

2) Use re.sub with/without callbacks

3) Use an existing templating solution (of which there are many in the Python 
world).

Exactly how far down that line you go depends on the complexity and
need for speed. But I'm surprised that the dictionary solution is that slow.
Especially since the code you quote above only actually makes one replacement before it returns the altered string :)

(You could probably squeeze a tiny bit more juice out of it my
iterating over the dict items rather than they keys:

for old, new in evildict.items ():
 text = text.replace (old, new)

)
TJG
_______________________________________________
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to