Python regular expressions

Posted by LupusFatalis on Sat 23 May 2009 02:17 AM — 2 posts, 14,034 views.

#0
Ok, here's the deal. Like I said, I'm fairly new to python. I finally got a neat little script that takes a paragraph from the mud, breaks it into sentences, and forms a list out of those sentences. I have it remove from the paragraph list strings that are found in a second list. And then I have it all recompiled into a new string formatted in my own way. What I would like to do, is change this from using straight strings to comparing regular expressions. This way rather than trying to match something like...

"copper ore" "iron ore" etc... I could just match
"\w+ ore"

So here is the code I currently have, with the lists significantly cut down for readability.
def ProcessDesc():

	TempA = str(RoomDesc[0]).split('.')
	TempB = []

	RoomDesc.pop(0)

	for item in TempA:
		TempB.append(item.lstrip().rstrip()+'.')

	rDesc = ['It is so dark here, you can barely see your hands in front of your face.',
			'It is extremely dark here.',
			'It is very dark here.']

	for item in rDesc:
		if item in TempB: TempB.remove(item)

	nLine = ''

	for item in TempB:
		nLine = nLine + ' ' + item

	nLine = nLine.rstrip(' .').lstrip()
	if not nLine == '': nLine = nLine + '.'

	#Long Description List
	lDesc = ['The rose-gold light of dawn',
		'The morning sun',
		'The midday sun']

	#Corresponding Short Description List
	sDesc = ['Light',
		'Light',
		'Light']

	for i, item in enumerate(lDesc):
		nLine = nLine.replace(lDesc[i], sDesc[i])

	while len(nLine) > wrapWidth:
		sChar = nLine[0:wrapWidth].rfind(' ')
		aLine = str(nLine[0:sChar])
		RoomDesc.append (aLine)
		nLine = ' ' + nLine[sChar:len(nLine)].lstrip()
	RoomDesc.append (nLine)
Amended on Sat 23 May 2009 02:18 AM by LupusFatalis
#1
I eventually got it... the important bit of code in what I have is...
	for x, itemA in  enumerate(reDesc):
		reText = re.compile(itemA)
		for y, itemB in enumerate(TempB):
			TempB[y] = re.sub(reText, sDesc[x], TempB[y])


where reDesc is an ordered list of regular expressions
and sDesc is an ordered list of strings corresponding to the regex list.
TempB in this case is a list of strings I want to scan through for matching regular expressions

works wonderfully, just figured I'd share if anyone cared to see my eventual solution.