简体   繁体   中英

Obtain house number from street address

Set-up

I have strings containing UK format addresses, eg address = '6A McCarthy Way' .

I need to obtain the house number from the address, eg house_number = '6A


Current Code

I have the following working code,

position = re.search('\d+', address).start()

if position == 0:
    for i in range(0,100000):    
        if address[position + i] != ' ':
            house_number = address[:position + i + 1]    
        else:
            break
else:
    house_number = address[position:]     

For both address = '6A McCarthy Way' and address = 'McCarthy Way 6A' , the code returns house_number = '6A' .


Problem

This code assumes that

  • the house number will either be at the beginning or end of address
  • the house number and address will be of the above 2 formats only – eg never address = '6A, McCarthy Way' or address = '6 McCarthy Way'
  • there are no mistakes in address – eg never address = '6AMcCarthy Way'

Lastly, even if the assumptions hold for all cases, I'm not sure this is the most pythonic way of doing it.

How can I improve the code?

Using re.search

import re
address = '6A McCarthy Way' 
address2 = 'McCarthy Way 6A'
address3 = 'McCarthy Way 6AAAA'

print(re.search("(\d+\w*)", address).group())
print(re.search("(\d+\w*)", address2).group()) 
print(re.search("(\d+\w*)", address3).group())

Output:

6A
6A
6AAAA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM