Conversion of perl based regex to python method

Peter Otten __peter__ at web.de
Thu May 25 08:25:08 CEST 2006


Andrew Robert wrote:

Wanted:

> perl -ple 's/([^\w\s])/sprintf("%%%2X", ord $1)/ge'  somefile.txt

Got:

> # Evaluate captured character as hex
> def ret_hex(ch):
>     return chr((ord(ch) + 1) % )

Make it compile at least before posting :-)
 
> # Evaluate the value of whatever was matched
> def eval_match(match):
>     return ret_hex(match.group(0))
> 
> # open file
> file = open(r'm:\mq\mq\scripts\testme.txt','r')
> 
> # Read each line, pass any matches on line to function
> for line in file.readlines():
>     re.sub('[^\w\s]',eval_match, line)

for line in file:
    ...

without readlines() is better because it doesn't read the whole file into
memory first. If you want to read data from files passed as commandline
args or from stdin you can use fileinput.input():

import re
import sys
import fileinput

def replace(match):
    return "%%%2X" % ord(match.group(0))

for line in fileinput.input():
    sys.stdout.write(re.sub("[^\w\s]", replace, line))

Peter




More information about the Python-list mailing list