[Python] Looking for a better way to parse address string

Discussão em 'Python' iniciado por Stack, Junho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I have a dict of addresses and I need to parse each address for the town, state, and zip code. And of course each address entry is not uniform.

    Most are the "standard" format of street address, town, state, zip


    123 Anywhere St. Some Town, NE 12345
    ​

    But some will have an extra field at the beginning, such as:


    Wildlife Preservation X, 123 Anywhere St. Some Town, NE 12345
    ​

    And some others will only have the town, state, and zip:


    Some Town, NE 12345
    ​

    This bit of code works, but it just seems very inefficient and I'm thinking there's got to be a better, cleaner way

    # Address contains a name, then street address, town, state, zip, USA
    if each.origin_addresses.count(',') == 4:
    town = each.origin_addresses.split(', ')[2]
    state = each.origin_addresses.split(', ')[3].split(" ")[0]
    zip_code = each.origin_addresses.split(', ')[3].split(" ")[1]

    # Address contains street address, town, state, zip, USA
    elif each.origin_addresses.count(',') == 3:
    town = each.origin_addresses.split(', ')[1]
    state = each.origin_addresses.split(', ')[2].split(" ")[0]
    zip_code = each.origin_addresses.split(', ')[2].split(" ")[1]

    # Address contains town, state, zip, USA
    elif each.origin_addresses.count(',') == 2:
    town = each.origin_addresses.split(', ')[0]
    state = each.origin_addresses.split(', ')[1].split(" ")[0]
    zip_code = each.origin_addresses.split(', ')[1].split(" ")[1]`


    Thanks

    Continue reading...

Compartilhe esta Página