regex/lambda black magic
Andrew Robert
andrew.arobert at gmail.com
Thu May 25 14:33:00 EDT 2006
Hi Everyone,
Thanks for all of your patience on this.
I finally got it to work.
Here is the completed test code showing what is going on.
Not cleaned up yet but it works for proof-of-concept purposes.
#!/usr/bin/python
import re,base64
# Evaluate captured character as hex
def ret_hex(value):
return '%'+base64.b16encode(value)
# Evaluate the value of whatever was matched
def enc_hex_match(match):
return ret_hex(match.group(0))
def ret_ascii(value):
return base64.b16decode(value)
# Evaluate the value of whatever was matched
def enc_ascii_match(match):
arg=match.group()
#remove the artifically inserted % sign
arg=arg[1:]
# decode the result
return ret_ascii(arg)
def file_encoder():
# Read each line, pass any matches on line to function for
# line in file.readlines():
output=open(r'e:\pycode\sigh.new','wb')
for line in open(r'e:\pycode\sigh.txt','rb'):
output.write( (re.sub('[^\w\s]',enc_hex_match, line)) )
output.close()
def file_decoder():
# Read each line, pass any matches on line to function for
# line in file.readlines():
output=open(r'e:\pycode\sigh.new2','wb')
for line in open(r'e:\pycode\sigh.new','rb'):
output.write(re.sub('%[0-9A-F][0-9A-F]',enc_ascii_match, line))
output.close()
file_encoder()
file_decoder()
More information about the Python-list
mailing list