gpt4 book ai didi

Python正则表达式从地址中分离街道和号码

转载 作者:行者123 更新时间:2023-12-01 06:34:37 24 4
gpt4 key购买 nike

我想分割街道和号码。

这是我当前的解决方案:

matches = re.match(r'^(?<street>[^,]*?)[,\s]*(?P<number>\d[\w\s\-/]*$)', street_number)

但在某些情况下它不起作用。如果我有这样的例子:

working_examples = [
'Somestreet 1',
'Somestreet1',
'Somestreet1a',
'Somestreet 1a',
'Somestreet 1 a'
]

print(matches.groupdict()) 打印working_examples 的第一个元素:

{'street': 'Somestreet', 'number': '1'}

但是在这种情况下:

not_working_examples = [
'Some 1 street',
'Some 1a street'
]

打印

{'street': 'Some', 'number': '1 street'}

我的目标是

{'street': '某 1 条街', 'number': None}

最佳答案

import re


examples = [
'Somestreet 1',
'Somestreet1',
'Somestreet1a',
'Somestreet 1a',
'Somestreet 1 a',
'Some 1 street',
'Some 1a street'
]

for s in examples:
matches = re.match(r'^(?P<street>.+?)[,\s]*(?P<number>\d\s?\w?)$', s)
if matches:
print(matches.groups())
else:
print s, "doesn't match"

输出:

('Somestreet', '1')
('Somestreet', '1')
('Somestreet', '1a')
('Somestreet', '1a')
('Somestreet', '1 a')
Some 1 street doesn't match
Some 1a street doesn't match

Demo & explanation

关于Python正则表达式从地址中分离街道和号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59735683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com