regex/lambda black magic
Andrew Robert
andrew.arobert at gmail.com
Thu May 25 10:00:54 EDT 2006
Hi everyone,
I have two test scripts, an encoder and a decoder.
The encoder, listed below, works perfectly.
import re,sys
output = open(r'e:\pycode\out_test.txt','wb')
for line in open(r'e:\pycode\sigh.txt','rb') :
output.write( re.sub(r'([^\w\s])', lambda s: '%%%2X' %
ord(s.group()), line))
The decoder, well, I have hopes.
import re,sys
output = open(r'e:\pycode\new_test.txt','wb')
for line in open(r'e:\pycode\out_test.txt','rb') :
output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), 16))
% ord(s.group()), line))
The decoder generates the following traceback:
Traceback (most recent call last):
File "E:\pycode\sample_decode_file_specials_from_hex.py", line 9, in ?
output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), 16))
% ord(s.group()), line))
File "C:\Python24\lib\sre.py", line 142, in sub
return _compile(pattern, 0).sub(repl, string, count)
File "E:\pycode\sample_decode_file_specials_from_hex.py", line 9, in
<lambda>
output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), 16))
% ord(s.group()), line))
ValueError: invalid literal for int(): %
Does anyone see what I am doing wrong?
More information about the Python-list
mailing list