[re.finditer] Getting all occurences in one go?

G

Gilles Ganault

Hello

I'd like to make sure there isn't an easier way to extract all the
occurences found with re.finditer:

=======================
req = urllib2.Request(url, None, headers)
response = urllib2.urlopen(req).read()
matches = re.compile("(\d+).html").finditer(response)
# ----------- BEGIN
for match in matches:
if mytable[item]=="":
mytable[item]= match.group(1)
else:
mytable[item]= mytable[item] + "," + match.group(1) #
----------- END
=======================

Can the lines between BEGIN/END be simplified so I can copy all the
items into the mytable[] dictionary in one go, instead of getting each
one in a row, and append them with a comma, eg.

# I want this : mytable[123] = 6548,8457,etc."
# DOESN' T WORK
# mytable[item] = matches.group(0)
mytable[item] = matches.getall()

Thank you.
 
G

Gilles Ganault

I'd like to make sure there isn't an easier way to extract all the
occurences found with re.finditer:

Oops, s/match/item/:

req = urllib2.Request(url, None, headers)
response = urllib2.urlopen(req).read()
matches = re.compile("(\d+).html").finditer(response)
# ----------- BEGIN
for item in matches:
if mytable[item]=="":
mytable[item]= match.group(1)
else:
mytable[item]= mytable[item] + "," + match.group(1) #
----------- END
 
P

Paul Rubin

Gilles Ganault said:
for match in matches:
if mytable[item]=="":
mytable[item]= match.group(1)
else:
mytable[item]= mytable[item] + "," + match.group(1) #
----------- END
=======================

Can the lines between BEGIN/END be simplified so I can copy all the
items into the mytable[] dictionary in one go, instead of getting each
one in a row, and append them with a comma, eg.

Yes, look at the string.join method and generator expressions. You'd
say:

mytable[item] = ','.join(m.group(1) for m in matches)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top