我在 Python 2.7 中有一個帶有正則運算式的小腳本,可以識別街道或大道名稱何時在字串中。但是它不適用于只有兩個字母的街道名稱(好吧,這非常罕見)或帶有數字的街道(例如 29th Street)...我想編輯它以使后者作業(例如識別 29th Street 或 1st街道)。
這有效:
import re
def street(search):
if bool(re.search('(?i)street', search)):
found = re.search('([A-Z]\S[a-z] \s(?i)street)', search)
found = found.group()
return found.title()
if bool(re.search('(?i)avenue', search)):
found = re.search('([A-Z]\S[a-z] \s(?i)avenue)', search)
found = found.group()
return found.title()
else:
found = "na"
return found
userlocation = street("I live on Stackoverflow Street")
print userlocation
或者,使用“Stackoverflow Avenue”
......但這些失敗:
userlocation = street("I live on SO Street")
userlocation = street("I live on 29th Street")
userlocation = street("I live on 1st Avenue")
userlocation = street("I live on SO Avenue")
出現此錯誤(因為沒有找到)
me@me:~/Documents/test$ python2.7 test_street.py
Traceback (most recent call last):
File "test_street.py", line 12, in <module>
userlocation = street("I live on 29th Street")
File "test_street.py", line 6, in street
found = found.group()
AttributeError: 'NoneType' object has no attribute 'group'
除了更正查詢以使其識別“1st”、“2nd”、“80th”、“110th”等之外,如果找不到任何東西,我還希望避免致命錯誤。
uj5u.com熱心網友回復:
您可以在函式中合并您的兩個條件,然后您可以匹配任何非空格字符\S ,后跟空格和關鍵字“ Street ”或“ Avenue ”(\s(Street|Avenue))。
import re
def street(search):
if bool(re.search('(?i)(street|avenue)', search)):
found = re.search('(?i)\S \s(Street|Avenue)', search)
found = found.group()
return found.title()
else:
found = "na"
return found
print street("I live on Stackoverflow Street")
print street("I live on SO street")
print street("I live on 29th Street")
print street("I live on 1st Avenue")
print street("I live on SO Avenue")
輸出:
Stackoverflow Street
So Street
29Th Street
1St Avenue
So Avenue
這將僅匹配街道的最后一個單詞,但如果您想匹配多字街道并且您能夠捕獲始終出現在街道之前的特定關鍵字,那么您可能能夠捕獲整個街道名稱。
在此處查看正則運算式演示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/498072.html
標籤:Python 正则表达式 python-2.7 无类型
