免责声明:我非常仔细地阅读了这个帖子: Street Address search in a string - Python or Ruby 以及许多其他资源。
到目前为止对我没有任何作用。
更多细节是我正在寻找的是:
规则很宽松,我绝对不是要求一个涵盖所有情况的完美代码;只是一些简单的基本内容,假设地址应采用以下格式:
a) Street number (1...N digits);
b) Street name : one or more words capitalized;
b-2) (optional) would be best if it could be prefixed with abbrev. "S.", "N.", "E.", "W."
c) (optional) unit/apartment/etc can be any (incl. empty) number of arbitrary characters
d) Street "type": one of ("st.", "ave.", "way");
e) City name : 1 or more Capitalized words;
f) (optional) state abbreviation (2 letters)
g) (optional) zip which is any 5 digits.
以上都不需要是有效的东西(例如现有的城市或邮政编码)。
到目前为止,我正在尝试这样的表达方式:
pat = re.compile(r'\d{1,4}( \w+){1,5}, (.*), ( \w+){1,5}, (AZ|CA|CO|NH), [0-9]{5}(-[0-9]{4})?', re.IGNORECASE)
>>> pat.search("123 East Virginia avenue, unit 123, San Ramondo, CA, 94444")
不工作,对我来说,这并不容易理解为什么。具体来说:我如何在我的模式中将一组任何单词与一个应该跟随的特定单词分开,比如状态缩写。或街道类型(“st., ave.)?
无论如何:这是我希望得到的一个例子: 鉴于 def ex_addr(文本): # 重新施魔法 # 返回第一个地址(所有地址?)或者如果没有找到则返回 None
for t in [
'The meeting will be held at 22 West Westin st., South Carolina, 12345 on Nov.-18',
'The meeting will be held at 22 West Westin street, SC, 12345 on Nov.-18',
'Hi there,\n How about meeting tomorr. @10am-sh in Chadds @ 123 S. Vancouver ave. in Ottawa? \nThanks!!!',
'Hi there,\n How about meeting tomorr. @10am-sh in Chadds @ 123 S. Vancouver avenue in Ottawa? \nThanks!!!',
'This was written in 1999 in Montreal',
"Cool cafe at 420 Funny Lane, Cupertino CA is way too cool",
"We're at a party at 12321 Mammoth Lane, Lexington MA 77777; Come have a beer!"
] print ex_addr(t)
我想得到:
'22 West Westin st., South Carolina, 12345' '22 West Westin street, SC, 12345' '123 S. Vancouver ave. in Ottawa' '123 S. Vancouver avenue in Ottawa' None # for 'This was written in 1999 in Montreal', "420 Funny Lane, Cupertino CA", "12321 Mammoth Lane, Lexington MA 77777"
你能帮忙吗?
最佳答案
我刚刚在 GitHub 上遇到了这个问题,因为我遇到了类似的问题。似乎有效,并且比您当前的解决方案更强大。
https://github.com/madisonmay/CommonRegex
查看代码,街道地址的正则表达式可用于更多场景。 '\d{1,4} [\w\s]{1,20}(?:street|st|avenue|ave|road|rd|highway|hwy|square|sq|trail|trl|drive|dr| court|ct|parkway|pkwy|circle|cir|boulevard|blvd)\W?(?=\s|$)'
关于python - 在文本中查找美国街道地址(最好使用 Python 正则表达式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18368086/