[英]Obtain house number from street address
Set-up设置
I have strings containing UK format addresses, eg address = '6A McCarthy Way'
.我有包含英国格式地址的字符串,例如address = '6A McCarthy Way'
。
I need to obtain the house number from the address, eg house_number = '6A
我需要从地址中获取门牌号,例如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'
.对于address = '6A McCarthy Way'
和address = 'McCarthy Way 6A'
,代码返回house_number = '6A'
。
Problem问题
This code assumes that此代码假设
address
门牌号码将在address
的开头或结尾address = '6A, McCarthy Way'
or address = '6 McCarthy Way'
门牌号和地址只能是上述 2 种格式——例如从不address = '6A, McCarthy Way'
或address = '6 McCarthy Way'
address
– eg never address = '6AMcCarthy Way'
address
没有错误——例如从不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.最后,即使假设适用于所有情况,我也不确定这是最 Pythonic 的方法。
How can I improve the code?如何改进代码?
Using re.search
使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.