tags:

views:

95

answers:

3

what would be the best way to split this in python. (address, city, state, zip)

<div class="adtxt">7616 W Belmont Ave<br />Chicago, IL 60634-3225</div>

in some case zip code is as

 <div class="adtxt">7616 W Belmont Ave<br />Chicago, IL 60634</div>
+3  A: 

Depending on how tight or lax you want to be on various aspects that can't be deduced from a single example, something like the following should work...:

import re

s = re.compile(r'^<div.*?>([^<]+)<br.*?>([^,]+), (\w\w) (\d{5}-\d{4})</div>$')
mo = s.match(thestring)
if mo is None:
  raise ValueError('No match for %r' % thestring)
address, city, state, zip = mo.groups()
Alex Martelli
obligatory: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454
teepark
the works fine, but if the zip is only 5 digits, it throws error
bobsr
replace `(\d{5}-\d{4})` at the end of regexp with `(\d{5}-\d{4}|\d{5})`
cji
Also - really, really read linked by teepark answer...
cji
@bobsr, I _do_ explain it depends on how strict or lax you want to be on conditions that are impossible to deduce from a single example -- if the only variation (as per your edit) is in the zipcode, @cji's solution fixes that; if there's more variation, you need more and more tweaks.
Alex Martelli
And BTW, I agree that the parsing of the tag themselves could best be done by an HTML parser, but if you do that you still need further processing for the city / state / zip separation.
Alex Martelli
A: 

Just a hint: there are much better ways to parse HTML than regular expressions, for example Beautiful Soup.

Here's why you shouldn't do that with regular expressions.

EDIT: Oh well, @teepark linked it first. :)

vtorhonen
A: 

Combining beautifulsoup and the regular expressions should give you something like:

import BeautifulSoup
import re
thestring = r'<div class="adtxt">7616 W Belmont Ave<br />Chicago, IL 60634-3225</div>'
re0 = re.compile(r'(?P<address>[^<]+)')
re1 = re.compile(r'(?P<city>[^,]+), (?P<state>\w\w) (?P<zip>\d{5}-\d{4})')
soup = BeautifulSoup.BeautifulSoup(thestring)
(address,) = re0.search(soup.div.contents[0]).groups()
city, state, zip = re1.search(soup.div.contents[2]).groups()
DiggyF
this works fine, but if the zip is only 5 digits (60634), it throws error
bobsr