re.complile failure in a SageWS (Vertical Bar character)
I was trying to use a Python Cookbook recipe (https://www.safaribooksonline.com/lib...) for multiple regular expression matches and substitutions in a Sagemath Cloud Sage Worksheet (final usage is for altering the __latex_/_repr_ attributes of an object). The code from the cookbook is below:
import re
def multiple_replace(txt, adict):
rx = re.compile('|'.join(map(re.escape, adict)))
def one_xlat(match):
return adict[match.group(0)]
return rx.sub(one_xlat, txt)
txt = "Larry Wall is the creator of Perl"
adict = {
"Larry Wall" : "Guido van Rossum",
"creator" : "Benevolent Dictator for Life",
"Perl" : "Python",
}
print(multiple_replace(txt, adict))
When I run this code in the Worksheet I get the error:
Error in lines 13-13
Traceback (most recent call last):
File "/projects/PROJECT/sagemathcloud/sage_server.py", line 873, in execute
exec compile(block+'\n', '', 'single') in namespace, locals
File "", line 1, in <module>
File "", line 5, in multiple_replace
File "", line 4, in one_xlat
IndexError: no such group
If I run the same code on a Sagemath Cloud IPython Notebook, Windows/Linux Python 2.7 session, or Windows/Linux Python 3.4 session the code outputs the correct result.
I started debugging and found that Sage doesn't like the '|'
in the compiled string. If I change the character to another (e.g. ','
) I no longer get the error ... though the code no longer functions with anything other than the '|'
. I also tried to substitute '|'
with unichr(int('007c', 16))
which results in the same error.
Has anyone seen anything like this before? I tried to search for it, but it seems so niche I didn't find any results. Any ideas for a workaround?
Thanks Matt