Regex loop question

Mike P michael.pearmain at tangozebra.com
Mon Mar 3 04:43:32 EST 2008


Hi Experts,

I've written a peice of code that works fine and fits, and passes
values into a peice of SPSS code, the problem is that it is not
dynamic, and so i though about how i can make it dynamic, (other code
may not have upto 10 some may have more) and came up with regex for an
idea, but i can't seem to make it work, can anyone offer any advice?
Below is current working code

time_variables = {"ActivityTime": "Activity_Time",
		"ExposureTime_Last":"Exposure_Time_1",
		"ExposureTime_Last2":"Exposure_Time_2",
		"ExposureTime_Last3":"Exposure_Time_3",
		"ExposureTime_Last4":"Exposure_Time_4",
		"ExposureTime_Last5":"Exposure_Time_5",
		"ExposureTime_Last6":"Exposure_Time_6",
		"ExposureTime_Last7":"Exposure_Time_7",
		"ExposureTime_Last8":"Exposure_Time_8",
		"ExposureTime_Last9":"Exposure_Time_9",
		"ExposureTime_Last10":"Exposure_Time_10"}

for Var in time_variables.keys():
	time_manips = ("""COMPUTE %s = SUBSTR(%s,(INDEX(%s,'T'))+1) .
	COMPUTE %s = number(%s, TIME8).
	VARIABLE LABEL %s.
	VARIABLE LEVEL %s (SCALE).
	FORMATS %s (TIME8).
	VARIABLE WIDTH %s (8).
	EXECUTE.""") %(Var, Var,
Var,time_variables[Var],Var,time_variables[Var],time_variables[Var],time_variables[Var],time_variables[Var])
	spss.Submit(time_manips)


Now to make it dynamic i've gone for the following...

reg_time = re.compile("^ExposureTime_Last([0-9]*)$")
reg_Activity = re.compile("^ActivityTime")
for Var in time_variables.keys():
    if reg_time.match(Var):
        match = reg_time.match(Var)
        E_time = "Exposure_Time_%s" % match.groups()[0]
    else:
        match = reg_time.match(Var)
        match.groups()[0] = "Activity_Time"


	time_manips = ("""COMPUTE %s = SUBSTR(%s,(INDEX(%s,'T'))+1) .
	COMPUTE %s = number(%s, TIME8).
	VARIABLE LABEL %s.
	VARIABLE LEVEL %s (SCALE).
	FORMATS %s (TIME8).
	VARIABLE WIDTH %s (8).
	EXECUTE.""") %(Var, Var,
Var,time_variables[Var],Var,time_variables[Var],time_variables[Var],time_variables[Var],time_variables[Var])
	print(time_manips)

All help welcome, or if a different approach is better please let me
know

Mike





More information about the Python-list mailing list